LeetCode-Sort List
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; } while (head1 != null){ tail.next = head1;
head1 = head1.next;
tail = tail.next;
} while(head2 != null){ tail.next = head2;
head2 = head2.next;
tail = tail.next;
} 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 的作用
二刷:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
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(right, left);
}
public ListNode merge (ListNode head1, ListNode head2){
ListNode dummy = new ListNode(-1);
ListNode temp = dummy;
while(head1 != null && head2 != null){
if(head1.val < head2.val){
temp.next = head1;
head1 = head1.next;
}
else{
temp.next = head2;
head2 = head2.next;
}
temp = temp.next;
}
if(head1 != null){
temp.next = head1;
//head1 = head1.next;
//temp = temp.next;
}
if(head2 != null){
temp.next = head2;
//head2 = head2.next;
//temp = temp.next;
}
return dummy.next;
}
public ListNode findMid(ListNode head){
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast =fast.next.next;
}
return slow;
}
}
posted on 2015-03-09 23:13 IncredibleThings 阅读(99) 评论(0) 收藏 举报
浙公网安备 33010602011771号