2014年5月10日星期六

LinkedList Solution - Partition List

The idea is to create two 'sub lists', then append to each. The only place easier to have mistake is the reference. The current node (next) pointer needs to be cleaned before add to list, otherwise will loop back and forth. Before cleaning it, get the next first otherwise lose it since pointer cleaned.

/**
 * 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 firHead = new ListNode(Integer.MIN_VALUE);
        ListNode secHead = new ListNode(Integer.MIN_VALUE);
        ListNode firNode = firHead;
        ListNode secNode = secHead;
       
        ListNode node = head;
        while(node != null){
            ListNode next = node.next;
            node.next = null;
            if(node.val < x){
                firNode.next = node;
                firNode = firNode.next;
            }else{
                secNode.next = node;
                secNode = secNode.next;
            }
            node = next;
        }
       
        firNode.next = secHead.next;
       
        return firHead.next;
       
        // ListNode firstBigger = head;
        // ListNode lastSmaller = head;
        // if(head.val >= x){
        //     firstBigger = head;
        //     lastSmaller = null;
        // }else{
        //     firstBigger = head.next;
        //     while(firstBigger != null){
        //         if(firstBigger.val < x){
        //             lastSmaller = firstBigger;
        //             firstBigger = firstBigger.next;
        //         }else{
        //             break;
        //         }
        //     }
        // }
        // if(firstBigger == null){
        //     return head;
        // }
        // ListNode node = firstBigger.next;
        // ListNode pre = firstBigger;
        // while(node != null){
        //     if(node.val < x){
        //         ListNode temp = node.next;
        //         node.next = firstBigger;
        //         if(lastSmaller != null){
        //             lastSmaller.next = node;
        //         }else{
        //             head = node;
        //         }
        //         lastSmaller = node;
        //         node = temp;
        //         pre.next = node;
        //     }else{
        //         pre = node;
        //         node = node.next;
        //     }
        // }
        // return head;
    }
}

没有评论: