做了一段时间的leetcode,别看leetcode的算法基础,边界条件cover的非常全面,
题目要求时间复杂度O(n log n),空间复杂度为常量,首先想到快速排序,堆排序,但这两种算法比较适用于数组,
就决定用非常基本的并归排序算法,通过调整node的位置,进行二路合并
思路虽然简单,遇到相同 val的节点,一不小心会丢失,终于找到了原因,分析并通过,总结一下,帮助提高。
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null||head.next ==null)return head;
ListNode ans = null;
ListNode slow = null,fast = null;
for(slow = head,fast = head;fast.next != null&&fast.next.next != null;
slow = slow.next,fast = fast.next.next);
ListNode head2 = slow.next;
slow.next = null;
if(head != slow){
ans = merge(head,head2);
}else{
if(head.val>head2.val){
ans = head2;
head2.next = head;
}else{
head.next = head2;
ans = head;
}
}
return ans;
}
ListNode merge(ListNode head1,ListNode head2){
ListNode slow = null,fast = null;
if(head1.next == null){
//*************one node in list1, do nothing**********
}else if(head1.next.next == null){
//*************two node in list1, judge and adjust*********
if(head1.val > head1.next.val){
head1.next.next = head1;
head1 = head1.next;
head1.next.next = null;
}
}else{
//***************more than two node in list1, recursion*********
for(slow = head1,fast = head1;fast.next != null&&fast.next.next != null;
slow = slow.next,fast = fast.next.next);
ListNode tmp = slow.next;
slow.next = null;
head1 = merge(head1,tmp);
}
if(head2.next == null){
//*************one node in list2, do nothing**********
}else if(head2.next.next==null){
//*************two node in list2, judge and adjust*********
if(head2.val > head2.next.val){
head2.next.next = head2;
head2 = head2.next;
head2.next.next=null;
}
}else{
//***************more than two node in list2, recursion*********
for(slow = head2,fast = head2;fast.next != null&&fast.next.next != null;
slow = slow.next,fast = fast.next.next);
ListNode tmp = slow.next;
slow.next = null;
head2 = merge(head2,tmp);
}
ListNode ans = null;
if(head1.val > head2.val) ans = head2;
else ans = head1;
while(head1!=null && head2!=null){
ListNode tmp = null;
/****
* 在合并阶段,非常关键,小心丢失相同元素
* head1.val == head2.val 时,head1向前推进;
* 所以当head1.next.val == head2.val, 不能改变head1.next,直接后移
* 当head2.next.val == head1.val, 要改变head2.next指向head1,head2再向后移。
*/
if(head1.val > head2.val) {
tmp = head2.next;
if(tmp!=null){
if(tmp.val < head1.val){ //这里不能有 =
head2 = head2.next;
}else{
head2.next = head1;
head2 = tmp;
}
}else{
head2.next = head1;
head2 = null;
}
}else{
tmp = head1.next;
if(tmp!=null){
if(tmp.val <= head2.val){//head1.next.val == head2.val 时 , head1后移但不改变head1.next指向head2
head1 = head1.next; //这里要有 =
}else{
head1.next = head2;
head1 = tmp;
}
}else{
head1.next = head2;
head1 = null;
}
}
}
return ans;
}
}