-
Notifications
You must be signed in to change notification settings - Fork 6
/
PartitionList.java
46 lines (44 loc) · 1.2 KB
/
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
37
38
39
40
41
42
43
44
45
46
package io.ziheng.list.leetcode;
import io.ziheng.list.leetcode.ListNode;
/**
* LeetCode 86. Partition List
* https://leetcode.com/problems/partition-list/
*/
public class PartitionList {
/**
* Partition Linked List
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* @param head
* @param x
* @return ListNode
*/
public ListNode partition(ListNode head, int x) {
if (head == null) {
return head;
}
ListNode pLess = new ListNode(0);
ListNode pGreater = new ListNode(0);
ListNode pLessHead = pLess;
ListNode pGreaterHead = pGreater;
ListNode currentNode = head;
while (currentNode != null) {
ListNode nextNode = currentNode.next;
if (currentNode.val < x) {
currentNode.next = null;
pLess.next = currentNode;
pLess = currentNode;
} else {
currentNode.next = null;
pGreater.next = currentNode;
pGreater = currentNode;
}
currentNode = nextNode;
}
pLess.next = pGreaterHead.next;
return pLessHead.next;
}
}
/* EOF */