标签:
很简单一道题,就是细节容易出错,必然是二分才有nlogn的速度
public class Solution { public ListNode sortList(ListNode head) { // 跟merge sort 一模一样 http://www.cnblogs.com/jiajiaxingxing/p/4397354.html if(head==null ||head.next==null) return head; ListNode h = new ListNode(-1); h.next = head; ListNode run=head, walk = head; while(run.next!=null && run.next.next!=null){ run = run.next.next; walk=walk.next; } ListNode lft = head,rt = walk.next; walk.next= null; if(lft!=rt){ // 忘了加这个!!!! lft = sortList(lft); rt = sortList(rt); } return merge2list(lft,rt); } public ListNode merge2list(ListNode lft, ListNode rt){ if(lft==null) return rt; // 忘了加这个!!!! if(rt==null) return lft; // 忘了加这个!!!! ListNode h = new ListNode(-1); ListNode cur = h; while(lft!=null && rt!=null){ if(lft.val<rt.val){ cur.next = lft; lft = lft.next; cur = cur.next; }else{ cur.next = rt; rt = rt.next; cur = cur.next; } } if(lft!=null && rt==null) cur.next = lft; if(lft==null && rt!=null) cur.next = rt; return h.next; } }
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4413426.html