您的位置:首页 > 其它

Sort List

2016-12-14 14:11 337 查看
Sort a linked list in O(n log n)
time using constant space complexity.

Merge sort

/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
return helper(head);
}

private ListNode helper(ListNode head) {
//base case
if(head == null || head.next == null) {
return head;
}
ListNode middle = findMiddle(head);
ListNode right = helper(middle.next);
middle.next = null;
ListNode left = helper(head);
return merge(left, right);
}

private ListNode findMiddle(ListNode head) {
ListNode slow = head, fast = head.next;
while(fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}

private ListNode merge(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while(left != null && right != null) {
if(left.val < right.val) {
head.next = left;
left = left.next;
} else {
head.next = right;
right = right.next;
}
head = head.next;
}
if(left != null) {
head.next = left;
}
if(right != null) {
head.next = right;
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linked list merge sort