Given a linked list and a valuex, partition it such that all nodes less thanxcome before nodes greater than or equal tox.
You should preserve the original relative order of the nodes in each of the two partitions.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) {
return head;
}
ListNode less = new ListNode(0);
ListNode equalOrMore = new ListNode(0);
ListNode p1 = less;
ListNode p2 = equalOrMore;
ListNode curNode = head;
while (curNode != null) {
if (curNode.val < x) {
p1.next = curNode;
p1 = p1.next;
}
else {
p2.next = curNode;
p2 = p2.next;
}
curNode = curNode.next;
}
p2.next = null;
p1.next = equalOrMore.next;
return less.next;
}
}