标签:
Sort List
问题:
Sort a linked list in O(n log n) time using constant space complexity.
思路:
归并排序
我的代码:
public class Solution { public ListNode sortList(ListNode head) { if(head == null) return null; if(head.next == null) return head; ListNode mid = getMiddle(head); ListNode right = sortList(mid.next); mid.next = null; ListNode left = sortList(head); return mergeList(left,right); } public ListNode getMiddle(ListNode head) { ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } public ListNode mergeList(ListNode head1, ListNode head2) { ListNode dummy = new ListNode(-1); ListNode head = dummy; while(head1 != null && head2 != null) { if(head1.val < head2.val) { dummy.next = head1; head1 = head1.next; } else { dummy.next = head2; head2 = head2.next; } dummy = dummy.next; } if(head1 != null) dummy.next = head1; if(head2 != null) dummy.next = head2; return head.next; } }
学习之处:
slow fast方法得mid模板
public ListNode getMiddle(ListNode head) { ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; }
方法的图形化证明:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4330888.html