You should preserve the original relative order of the nodes in each of the two partitions.
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
/**
* 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){
return head;
}
ListNode leftDummy = new ListNode(-1);
ListNode rightDummy = new ListNode(-1);
ListNode right = rightDummy, left = leftDummy;
while(head != null){
if(head.val < x){
left.next = head;
left = head;
}else{
right.next = head;
right = head;
}
head = head.next;
}
right.next = null;
left.next = rightDummy.next;
return leftDummy.next;
}
}