码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode linkedList sort

时间:2014-08-04 17:09:37      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   问题   ar   div   算法   

链表排序:算法-归并排序

public class LinkedSort {

    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    private ListNode mergeList(ListNode head1,ListNode head2){
        if(head1==null){
            return head2;
        }else if(head2==null){
            return head1;
        }
        ListNode head=new ListNode(0);
        ListNode tmp=head;
        while(head1!=null&&head2!=null){
            if(head1.val<=head2.val){
                head.next=head1;
                head1=head1.next;
            }else{
                head.next=head2;
                head2=head2.next;
            }
            head=head.next;
        }
        while(head1!=null){
            head.next=head1;
            head1=head1.next;
            head=head.next;
        }
        while(head2!=null){
            head.next=head2;
            head2=head2.next;
            head=head.next;
        }
        return tmp.next;//注意另起一个新的节点
    }
    public ListNode sortList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode first=head;
        ListNode after=head;
        // two nodes要特别处理是两个节点的情况
        if(head.next.next==null){
            first=head.next;
            head.next=null;
            return mergeList(head, first);
        }
        
        while(after!=null){
            if(after.next!=null){
                after=after.next.next;
                first=first.next;
            }else{
                break;
            }
        }
        ListNode tmp=first.next;
        first.next=null;//这里容易出现问题,提前将后置节点归null
        ListNode head1=sortList(head);
        ListNode head2=sortList(tmp);
        return mergeList(head1, head2);
    }
    public static void main(String[] args){
        LinkedSort linkedSort=new LinkedSort();
        ListNode head1=new ListNode(9);
        head1.next=new ListNode(3);
        head1.next.next=new ListNode(4);
        head1.next.next.next=new ListNode(1);
        head1.next.next.next.next=new ListNode(5);
        ListNode head=linkedSort.sortList(head1);
        System.out.println("fuck");
        while(head!=null){
            System.out.println(head.val);
            head=head.next;
        }
        
    }
}

 

leetcode linkedList sort,布布扣,bubuko.com

leetcode linkedList sort

标签:des   style   blog   color   问题   ar   div   算法   

原文地址:http://www.cnblogs.com/csxf/p/3890230.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!