Skip to content

Commit c777dfb

Browse files
committed
Added Partition Linked list - Medium
1 parent 4cdc17a commit c777dfb

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Time: O(n)
3+
* Space: O(n)
4+
*/
5+
public ListNode partition(ListNode node, int x) {
6+
// Create two lists. One for nodes less than x and the other
7+
// For nodes greater than x. Iterate through the input list
8+
// building the lesser and greater list and merge at the end
9+
ListNode beforeStart = null;
10+
ListNode afterStart = null;
11+
ListNode beforeEnd = null;
12+
ListNode afterEnd = null;
13+
14+
while (node != null) {
15+
// Let us insert into the before and after lists
16+
ListNode next = node.next;
17+
node.next = null; // ??
18+
if (node.val < x) {
19+
// Insert into before list
20+
if (beforeStart == null) {
21+
beforeStart = node;
22+
beforeEnd = beforeStart;
23+
} else {
24+
beforeEnd.next = node;
25+
beforeEnd = node;
26+
}
27+
} else {
28+
// Insert into after list
29+
if (afterStart == null) {
30+
afterStart = node;
31+
afterEnd = afterStart;
32+
} else {
33+
afterEnd.next = node;
34+
afterEnd = node;
35+
}
36+
}
37+
node = node.next;
38+
}
39+
// Now we check if our before list == null, meaning we only
40+
// Have nodes that are greater so we return after
41+
if (beforeStart == null) return afterStart;
42+
43+
// Merge both before and after lists
44+
beforeEnd.next = afterStart;
45+
return beforeStart;
46+
}

0 commit comments

Comments
 (0)