-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPartitionList.java
More file actions
35 lines (35 loc) · 1.03 KB
/
PartitionList.java
File metadata and controls
35 lines (35 loc) · 1.03 KB
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class PartitionList {
public ListNode partition(ListNode head, int x) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode insertPos = dummy;
ListNode prev = dummy;
ListNode current = head;
while (current != null) {
if (current.val >= x) {
prev = current;
current = current.next;
} else if (current.val < x && insertPos == prev) {
prev = current;
current = current.next;
insertPos = insertPos.next;
} else {
ListNode next = current.next;
prev.next = current.next;
current.next = insertPos.next;
insertPos.next = current;
current = next;
insertPos = insertPos.next;
}
}
return dummy.next;
}
}