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的位置,简单易行,指的以后参考学习
- 对于left和right 分别sort也有讲究,right需在前,待mid.next = null之后,方可sort left要不进入了死循环了。
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; }
方法的图形化证明: