单链表排序

2017-10-11  本文已影响0人  xbinng
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
 class ListNode{
    int val;
    ListNode next;
    ListNode(int x){
        val=x;
        next=null;
    }
 }
public class Solution {
    public static ListNode sortList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode fast=head,slow=head;
        while(fast!=null&&fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        ListNode second=slow.next;
        slow.next=null;
        sortList(head);
        sortList(second);
        return merge(head,second);
    }
    public static ListNode merge(ListNode first,ListNode second){
        if(first==null){
            return second;
        }
        if(second==null){
            return first;
        }
        //先确定头结点
        ListNode head;
        if(first.val<second.val){
            head=first;
            first=first.next;
        }else{
            head=second;
            second=second.next;
        }
        ListNode p=head;
        
        
        while(first!=null&&second!=null){
            if(first.val<second.val){
                p.next=first;
                first=first.next;
            }else{
                p.next=second;
                second=second.next;
            }
            p=p.next;
        }
        
        while(first!=null){
            p.next=first;
            first=first.next;
        }
        while(second!=null){
            p.next=second;
            second=second.next;
        }
        
        /*
        if(first!=null){
            p.next=first;
        }
        if(second!=null){
            p.next=second;
        }*/
        return head;
    }
    
    public static void main(String[] args){
        ListNode l1=new ListNode(4); 
        ListNode l2=new ListNode(2); 
        ListNode l3=new ListNode(1); 
        ListNode l4=new ListNode(3);
        l1.next=l2;
        l2.next=l3;
        l3.next=l4;
        ListNode head=sortList(l1);
        while(head!=null){
            System.out.println(head.val);
            head=head.next;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读