-
Notifications
You must be signed in to change notification settings - Fork 15
/
partition-list.java
48 lines (44 loc) · 1.19 KB
/
partition-list.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
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
public ListNode partition(ListNode head, int x) {
// write your code here
if (head == null) {
return head;
}
ListNode leftHead = new ListNode(0);
ListNode rightHead = new ListNode(0);
ListNode leftRunner = leftHead;
ListNode rightRunner = rightHead;
ListNode runner = head;
ListNode next = null;
while (runner != null) {
next = runner.next;
if (runner.val < x) {
leftRunner.next = runner;
leftRunner = leftRunner.next;
} else {
rightRunner.next = runner;
rightRunner = rightRunner.next;
}
runner.next = null;
runner = next;
}
leftRunner.next = rightHead.next;
return leftHead.next;
}
}