-
Notifications
You must be signed in to change notification settings - Fork 2
/
PartitionList.java
36 lines (34 loc) · 952 Bytes
/
PartitionList.java
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
/**
* 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 || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (fast.next != null) {
if (fast.next.val >= x) {
fast = fast.next;
} else if (fast == slow) {
fast = fast.next;
slow = slow.next;
} else {
ListNode temp = fast.next;
fast.next = fast.next.next;
temp.next = slow.next;
slow.next = temp;
slow = slow.next;
}
}
return dummy.next;
}
}