Search This Blog

Thursday, December 13, 2012

LeetCode: Partition List

Partition List
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.

/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(head==null) return null;
        
        ListNode n1 = new ListNode(x-1);
        n1.next = head;
        head = n1;
            
        while(n1!=null){
            while(n1.next!=null && n1.next.val<x)
                n1=n1.next;
            if(n1.next==null) break;
            
            ListNode n2=n1.next;
            while(n2.next!=null && n2.next.val>=x)
                n2=n2.next;
            if(n2.next==null) break;
            
            ListNode n3=n2;
            while(n3.next!=null && n3.next.val<x)
                n3=n3.next;
                
            ListNode temp = n2.next;
            n2.next=n3.next;
            n3.next=n1.next;
            n1.next=temp;
        }
        
        head=head.next;
        return head;
    }
}

No comments: