-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpartition-list
41 lines (41 loc) · 1.16 KB
/
partition-list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
ListNode dummyNewHead = new ListNode(0);
ListNode dummyCur = dummyNewHead;
dummy.next = head;
ListNode spre = dummy;
ListNode bpre = null;
ListNode cur = dummy.next;
while (cur!=null) {
while (cur != null && cur.val < x) {
spre = cur;
cur = cur.next;
}
dummyCur.next = cur; // start of >= x
while (cur != null && cur.val>=x) {
bpre = cur;
cur = cur.next;
}
if (bpre!=null){
dummyCur = bpre;
dummyCur.next = null;
}
if (cur!=null) spre.next = cur;
}
if (dummyNewHead.next != null) spre.next = dummyNewHead.next;
return dummy.next;
}
}