Given 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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
=====================
Analysis:
There is no space requirement. Therefore, we can create 2 linked list, one stores the list nodes that are less than x, while another one stores the list nodes greater than or equal to x. After gone though all the list nodes in original linked list, we combine two of our newly created linked list and return its head node.
One thing need to be pointed out that, we MUST close the linked lists we newly created every time when we add a new node to either of them. This is because, if we didn't close the linked lists, when we combine these two linked lists, we may create a linked list cycle!!
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null) return null;
ListNode fakeNodeS = new ListNode(0);
ListNode fakeNodeL = new ListNode(0);
ListNode fakeSHead = fakeNodeS;
ListNode fakeLHead = fakeNodeL;
while(head!=null){
if(head.val<x) {
fakeNodeS.next = head;
fakeNodeS = fakeNodeS.next;
}
else{
fakeNodeL.next = head;
fakeNodeL = fakeNodeL.next;
}
head = head.next;
fakeNodeL.next = fakeNodeS.next = null;//!!!!!!!!!!!!!!!!!
}
// combine 2 link list
fakeNodeS.next=fakeLHead.next;
return fakeSHead.next;
}
}