Java for LeetCode 148 Sort List

Sort a linked list in O(n log n) time using constant space complexity.

解题思路:

归并排序、快速排序、堆排序都是O(n log n),由于优先级队列是用堆排序实现的,因此,我们使用优先级队列即可,JAVA实现如下:

    public ListNode sortList(ListNode head) {
    	if(head==null||head.next==null)
    		return head;
        Queue<ListNode> pQueue = new PriorityQueue<ListNode>(
                0,new Comparator<ListNode>() {//提交的时候不能加初始容量(第一个参数),否则报错
                    public int compare(ListNode l1, ListNode l2) {
                        return l1.val - l2.val;
                    }
                });
        while(head!=null){
        	pQueue.add(head);
        	head=head.next;
        }
        head=pQueue.poll();
        ListNode temp=head;
        while(pQueue.size()>0){
        	temp.next=pQueue.poll();
        	temp=temp.next;
        }
        temp.next=null;
        return head;
    }

 

posted @ 2015-06-04 22:29  TonyLuis  阅读(188)  评论(0编辑  收藏  举报