leetcode [148]Sort List
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
题目大意:
对链表进行排序
解法;
使用之前插排思想解决,待优化,效率较低。这里newHead的next为啥不用等于head呢?
因为算法具体的流程是如下的,相当于构造了两个list:
例如:
originally 1->3->2->null
helper: 0->null;
after the first loop:
original list :3->2->null
helper:0->1->null
after the second loop:
original list: 2->null
helper:0->1->3->null
after the third loop:
original list :null
helper:0->1->2->3-> null.
java:
class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode newHead=new ListNode(-1);
ListNode pre=newHead;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
while(pre.next!=null&& pre.next.val<cur.val){
pre=pre.next;
}
cur.next=pre.next;
pre.next=cur;
cur=next;
pre=newHead;
}
return newHead.next;
}
}
转载于//www.cnblogs.com/xiaobaituyun/p/10747173.html
还没有评论,来说两句吧...