标签:
Sort a linked list in O(n log n) time using constant space complexity.
这题的时间复杂度要求是O(n logn),很容易想到用mergeSort来解。
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode merge(ListNode head1, ListNode head2){ ListNode dummy = new ListNode(-1); ListNode tail = dummy; while(head1 != null && head2 != null){ if(head1.val < head2.val){ tail.next = head1; head1 = head1.next; } else { tail.next = head2; head2 = head2.next; } tail = tail.next; } if(head1 != null){ tail.next = head1; } if(head2 != null){ tail.next = head2; } return dummy.next; } public ListNode findMid(ListNode head){ ListNode slow = head; ListNode fast = head.next;//instead of = head to ensure slow is in the mid position while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; } public ListNode sortList(ListNode head) { if(head ==null || head.next == null){ return head; } ListNode mid = findMid(head); ListNode right = sortList(mid.next); mid.next=null; ListNode left = sortList(head); return merge(left,right); } }
其中值得注意的是,
1.在merge function里dummy前置节点和tail的作用,
2.以及findMin里ListNode fast = head.next的作用,
3.sortList中mid.next = null 的作用
标签:
原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4324822.html