`
hcx2013
  • 浏览: 83301 次
社区版块
存档分类
最新评论

Sort List

 
阅读更多

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

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
    	 if (head == null || head.next == null) {  
             return head;  
         } 
    	 ListNode first = head;
    	 ListNode second = head;
    	 while (first.next != null && first.next.next != null) {
    		 first = first.next.next;
    		 second = second.next;
    	 }
    	 ListNode head2 = second.next;
    	 second.next = null;
    	 ListNode leftlist = null;
    	 ListNode rightlist =null;
    	 if (head != head2) {
    		 leftlist = sortList(head);
    		 rightlist = sortList(head2);
    	 }
    	 return mergeTwoLists(leftlist, rightlist);
    }

	private ListNode mergeTwoLists(ListNode leftlist, ListNode rightlist) {
		// TODO Auto-generated method stub
		if (leftlist == null) {
			return rightlist;
		}
		if (rightlist == null) {
			return leftlist;
		}
		ListNode head = leftlist.val < rightlist.val ? leftlist : rightlist;
		ListNode cur1 = head == leftlist ? leftlist : rightlist;
		ListNode cur2 = head == leftlist ? rightlist : leftlist;
		ListNode pre = null;
		ListNode next = null;
		while (cur1 != null && cur2 != null) {
			if (cur1.val <= cur2.val) {
				pre = cur1;
				cur1 = cur1.next;
			} else {
				next = cur2.next;
				pre.next = cur2;
				cur2.next = cur1;
				pre = cur2;
				cur2 = next;
			}
		}
		pre.next = cur1 == null ? cur2 : cur1;
		return head;
	}
}

 

0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics