86. 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 tox.

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.

---

keep track the next node!!!

 

/**
 * 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) {
        
        
        // check
        //if(head == null)    return null;
        
        ListNode leftHead = new ListNode(0);
        ListNode rightHead = new ListNode(0);

        
        ListNode left = leftHead;
        ListNode right = rightHead;
        
        while(head != null){
            
            //!!!
            ListNode next = head.next;
            
            if(head.val < x){
                left.next = head;
                left = left.next;
                left.next = null;
            }else if(head.val >= x){
                right.next = head;
                right = right.next;
                right.next = null;
            }
            
            head = next;
        }
        
        if(rightHead.next == null)
            return leftHead.next;

        
        if(leftHead.next == null)
            return rightHead.next;
        
          
        
        left.next = rightHead.next;
        return leftHead.next;
    }
}

 

posted @ 2013-09-20 04:16  LEDYC  阅读(165)  评论(0)    收藏  举报