

public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
ListNode cur = pHead;
while(cur != null) {
if(cur.val < x) {
if(bs == null) {
bs = be = cur;
}else{
be.next = cur;
be = be.next;
}
}else{
if(as == null) {
as = ae = cur;
}else{
ae.next = cur;
ae = ae.next;
}
}
cur = cur.next;
}
//可能会出现都大于x或都小于x的情况,当都大于x时返回as节点即可,否则返回bs
if(bs == null) {
return as;
}
//拼接
be.next = as;
//预防最后一个节点的next值不为空
if(as != null) {
ae.next = null;
}
return bs;
}
}



public class PalindromeList {
public boolean chkPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
//找出链表的中间节点
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
//链表的反转
ListNode cur = slow.next;
while(cur != null) {
ListNode curN = cur.next;//记录cur的下一个节点防止丢失
//开始反转
cur.next = slow;
//slow和cur往后走
slow = cur;
cur = curN;
}
//判断回文,head从前往后走,slow从后往前走,直到相遇
while(head != slow) {
if(head.val != slow.val){
return false;
}
if(head.next == slow) {
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
}
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79?tpId=196&tqId=37064&ru=/exam/oj
只留下重复元素的一个


import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
//遍历指针
ListNode cur = head;
//指针当前和下一位不为空
while (cur != null && cur.next != null) {
//如果当前与下一位相等则忽略下一位
if (cur.val == cur.next.val)
cur.next = cur.next.next;
//否则指针正常遍历
else
cur = cur.next;
}
return head;
}
}
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024?tpId=196&tqId=37063&ru=/exam/oj
将重复元素全部删除

操作:
tmp指向newHead,以便后续的拼接while循环遍历原始链表。
如果当前节点cur的下一个节点存在且两者值相等,则进入内层while循环,跳过所有与cur值相同的节点,直到找到不重复的元素。
如果当前节点cur的下一个节点不存在或两者值不相等,则将cur添加到新链表中

while循环结束后,将tmp.next设为null。
newHead.next。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
ListNode cur = head;
ListNode newHead = new ListNode(-1); // 创建一个虚拟节点
ListNode tmp = newHead;//用来连接
while (cur != null) {
if (cur.next != null && cur.val == cur.next.val) {
// 跳过所有重复节点
while (cur.next != null && cur.val == cur.next.val) {
cur = cur.next;
}
} else {
// 将非重复节点添加到新链表中
tmp.next = cur;
tmp = tmp.next; // 移动tmp到新的节点
}
// 移动cur到下一个节点
cur = cur.next;
}
// 确保新链表的最后一个节点的next为null
tmp.next = null;
return newHead.next;
}
}