Partition List

public class Solution {
    public ListNode partition(ListNode head, int x) {
        if(head==null) return head;
        ListNode h = new ListNode(-1);
        h.next = head;
        //http://blog.csdn.net/linhuanmars/article/details/24446871 , 双指针大法好,很容易糊涂啊
        ListNode r = h, w = h; // 把 前半段和后半段不断衔接起来的方法就是观察r.next;
        
        while(r.next!=null){
            if(r.next.val<x){
                if(w==r){
                    r= r.next;
                }else{
                    ListNode next = r.next.next;
                    r.next.next = w.next;
                    w.next = r.next;
                    r.next =next;
                }
                w=w.next;
            }else{
                r = r.next;
            }
        }
        return h.next;
    }
}

想要不糊涂就用多余的存储空间,但是速度非常慢

参见http://www.cnblogs.com/springfor/p/3862392.html

代码copy

public ListNode partition(ListNode head, int x) {
        if(head==null||head.next==null)
            return head;
        
        ListNode small = new ListNode(-1);
        ListNode newsmallhead = small;
        ListNode big = new ListNode(-1);
        ListNode newbighead = big;
        
        while(head!=null){
            if(head.val<x){
                small.next = head;
                small = small.next;
            }else{
                big.next = head;
                big = big.next;
            }
            head = head.next;
        }
        big.next = null;
        
        small.next = newbighead.next;
        
        return newsmallhead.next;
    }

 

posted @ 2015-04-08 12:31  世界到处都是小星星  阅读(175)  评论(0编辑  收藏  举报