forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPartitionList.java
42 lines (37 loc) · 1.02 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
// TC : O(n)
// SC : O(1)
public ListNode partition(ListNode head, int x) {
ListNode smallerHead = new ListNode(-1);
ListNode greaterHead = new ListNode(-1);
ListNode sIt = smallerHead;
ListNode gIt = greaterHead;
ListNode it = head;
while(it!=null){
if(it.val <x){
// for smaller values
sIt.next = it;
it = it.next;
sIt =sIt.next;
} else{
// for equal or greater comparisons
gIt.next = it;
it = it.next;
gIt = gIt.next;
}
}
sIt.next = greaterHead.next;
gIt.next = null;
return smallerHead.next;
}
}