这种链表的思路一定要掌握:
两个dummy node各开一条临时链表,最后在拼接在一起。
一定得记得去环啊!!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null) {
return null;
}
ListNode dummyLeft = new ListNode(0);
ListNode dummyRight = new ListNode(0);
ListNode left = dummyLeft, right = dummyRight;
ListNode node = head;
while (node != null) {
if (node.val < x) {
left.next = node;
left = left.next;
} else {
right.next = node;
right = right.next;
}
node = node.next;
}
/////////////
right.next = null;
/////////////
left.next = dummyRight.next;
return dummyLeft.next;
// if (head == null) {
// return null;
// }
// ListNode dummy = new ListNode(0);
// dummy.next = head;
// ListNode cur = head;
// while (cur.val != x && cur.next != null) {
// cur = cur.next;
// }
// if (cur.val != x) {
// return head;
// }
// ListNode ln = head;
}
}