You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
Idea: Two pointers.
1) First add a dummy head in the beginning of the linked list to deal with the cases when the current head>= x that a <x node needs to be added before the current head.
2) Use two pointers: lessTail and pre. lessTail is to remember the last digit <x. pre is used to traverse the list.
3) When pre.next is a value >=x, just push pre forward.
4) When pre.next is a value <x, we need to swap it to right behind lessTail. As in the example in the question, when pre=3, pre.next=2, we need to swap the 2 to the back of 1 (lessTail). In this case, the element 2 is cut from the list and moved to the back of 1. So push lessTail forward by 1 step, but keep pre=3 the same since pre.next=5 is right the node we are going to check in the next run.
Time: O(n) Space: O(1)
Code:
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null||head.next==null)
return head;
ListNode dummy=new ListNode(Integer.MIN_VALUE);
dummy.next=head;
ListNode lessTail=dummy;
while(lessTail.next!=null&&lessTail.next.val<x)
lessTail=lessTail.next;
if(lessTail.next==null)
return dummy.next;
ListNode pre=lessTail.next;
while(pre.next!=null)
{
if(pre.next.val<x)
{
ListNode cur=pre.next;
pre.next=pre.next.next;
cur.next=lessTail.next;
lessTail.next=cur;
lessTail=lessTail.next;
}
else
{
pre=pre.next;
}
}
return dummy.next;
}
}
No comments:
Post a Comment