as火柴人

导航

leetcode(java)

86 
class
Solution { public ListNode partition(ListNode head, int x) { ListNode lowheader=new ListNode(0); ListNode low=lowheader; ListNode highheader=new ListNode(0); ListNode high=highheader; while(head!=null){ if(head.val<x){ low.next=head; head=head.next; low=low.next; low.next=null; }else{ high.next=head; head=head.next; high=high.next; high.next=null; } } low.next=highheader.next; return lowheader.next; } }

 148

class Solution {
    public ListNode sortList(ListNode head) {
        while(head==null||head.next==null){
            return head;
        }
        ListNode fast=head,low=head;
        ListNode pre=null;
        while(fast!=null&&fast.next!=null){
            pre=low;
            low=low.next;
            fast=fast.next.next;
        }
        pre.next=null;
        ListNode left=sortList(head);
        ListNode right=sortList(low);
        ListNode dummy=new ListNode(0);
        ListNode curr=dummy;
        while(left!=null&&right!=null){
            if(left.val<right.val){
                curr.next=left;
                left=left.next;
                curr=curr.next;
            }else{
                curr.next=right;
                right=right.next;
                curr=curr.next;
            }
        }
        if(left==null){
            curr.next=right;
        }
        if(right==null){
            curr.next=left;
        }
        return dummy.next;
    }
}

 

posted on 2019-02-25 21:36  as火柴人  阅读(96)  评论(0)    收藏  举报