
Sponsored
Sponsored
This approach involves using two separate linked lists to store nodes that are less than x and nodes that are greater than or equal to x. You traverse the original list and attach each node to the appropriate list. Finally, you connect the two lists together to form the partitioned list.
Time Complexity: O(n), where n is the number of nodes in the list.
Space Complexity: O(1), as we only use a constant amount of extra space.
1public class ListNode {
2 public int val;
3 public ListNode next;
4 public ListNode(int x) { val = x; }
5}
6
7public class Solution {
8 public ListNode Partition(ListNode head, int x) {
9 ListNode lessHead = new ListNode(0);
10 ListNode greaterHead = new ListNode(0);
11 ListNode less = lessHead, greater = greaterHead;
12
13 while (head != null) {
14 if (head.val < x) {
15 less.next = head;
16 less = less.next;
17 } else {
18 greater.next = head;
19 greater = greater.next;
20 }
21 head = head.next;
22 }
23 greater.next = null;
24 less.next = greaterHead.next;
25 return lessHead.next;
26 }
27}In this C# solution, similar dummy nodes are used to help construct two separate lists easily. The greater list is attached to the end of the less list to form the final partitioned list.
This in-place rearrangement technique modifies the original list without the need of additional dummy nodes. This is accomplished by managing pointers to redefine segment connections efficiently.
Time Complexity: O(n)
Space Complexity: O(1)
1public class ListNode {
2 public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution {
public ListNode Partition(ListNode head, int x) {
ListNode beforeStart = null, beforeEnd = null, afterStart = null, afterEnd = null;
while (head != null) {
ListNode next = head.next;
head.next = null;
if (head.val < x) {
if (beforeStart == null) {
beforeStart = head;
beforeEnd = beforeStart;
} else {
beforeEnd.next = head;
beforeEnd = head;
}
} else {
if (afterStart == null) {
afterStart = head;
afterEnd = afterStart;
} else {
afterEnd.next = head;
afterEnd = head;
}
}
head = next;
}
if (beforeStart == null) {
return afterStart;
}
beforeEnd.next = afterStart;
return beforeStart;
}
}This C# implementation uses in-place rearrangement with four pointers to effectively organize nodes less than x and greater than or equal to x, achieving optimal partitioning.