Given the head of a linked list and a value x
, partition it such that all nodes less than x
come before nodes greater than or equal to x
.
You should preserve the original relative order of the nodes in each of the two partitions.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
x
(let’s call it less
) and one for nodes greater than or equal to x
(greater
).less
list or the greater
list based on its value.less
list to the beginning of the greater
list.less
list, skipping over the dummy head.class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null) return null;
// Initialize two dummy heads and their respective tails
ListNode lessHead = new ListNode(0);
ListNode greaterHead = new ListNode(0);
ListNode less = lessHead;
ListNode greater = greaterHead;
// Traverse the list and partition it
while (head != null) {
if (head.val < x) {
less.next = head;
less = less.next;
} else {
greater.next = head;
greater = greater.next;
}
head = head.next;
}
// Avoid cycle in the linked list by setting the next of greater to null
greater.next = null;
// Connect the end of less list to the start of greater list
less.next = greaterHead.next;
return lessHead.next;
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?