leetcode 鍊錶排序

2021-07-10 23:41:58 字數 2689 閱讀 2849

對鍊錶排序,用歸併排序。題目要求空間時間複雜度為o(nlogn),但是空間複雜度為o(1)

1.自己寫的程式,時間複雜度為o(nlogn),但是空間複雜度為o(n)

用快慢指標(分別走2步和1步)找到中間節點。但是最後排序的部分,用複製將排好序的部分貼上會原來鍊錶中,這個方法比較笨,而且增加空間複雜度,並不滿足題目要求

leetcode 提交的時候說runtime error,但自己執行是通過的,可能因為時間複雜度的原因吧,需要後期再改

void mergesort(listnode* head, listnode* as, listnode* ae, listnode* bs, listnode* be)

else

}while(ia <= anum)

while(ib <= bnum)

int pnum = pe - ps;

int ip = 0;

while(ip <= pnum)

}void merge(listnode* head,listnode* start, listnode* end)

if(latt+1 == snum)

merge(head,start,former);

merge(head,former->next,latter);

mergesort(head,start,former,former->next,end);

}else

return;

}

2.leetcode中大神的**,這裡貼上是為了自己以後找起來方便

它是自底向上的,歸併起來。step為1,2,4,8....

/**

* merge the two sorted linked list l1 and l2,

* return the tail of the merged sorted linked list

*/listnode* merge(listnode* l1, listnode* l2, listnode* head)

else

}cur->next = (l1 ? l1 : l2);

while(cur->next) cur = cur->next;

return cur;

}/**

* divide the linked list into two lists,

* while the first list contains first n ndoes

* return the second list's head

*/listnode* split(listnode *head, int n)

listnode *sortlist(listnode *head)

listnode dummy(0);

dummy.next = head;

listnode *left, *right, *tail;

for(int step = 1; step < length; step <<= 1)

}return dummy.next;

}

其餘補充的部分,對鏈結初始化和輸出列印部分

/**

* definition for singly-linked list.*/

struct listnode

};listnode* init(int a, int n)

q->next=p;

q = q->next;

}q->next = null;

return head;

}void prints(listnode* head)

}

int main(int argc, const char * argv) ;

//int a=;

listnode* head =new listnode(0);

head=init(a,8);

listnode* l = sortlist(head);

prints(l);

return 0;

}

3.最後提交上去的版本,能執行通過且過程簡單易懂,也是從別人那裡看到的

/**

* definition for singly-linked list.

* struct listnode

* };

*/class solution

else

}while(ia <= anum)

while(ib <= bnum)

int pnum = pe - ps;

int ip = 0;

while(ip <= pnum)

}void merge(listnode* head,listnode* start, listnode* end)

merge(head,start,former);

merge(head,former->next,latter);

mergesort(head,start,former,former->next,end);

}else

return;

} listnode* sortlist(listnode* head)

};

leetcode 鍊錶 排序

思路 使用歸併排序。拆分 合併均採用遞迴方式。public listnode sortlist listnode head pre.next null return merge sortlist head sortlist slow public listnode merge listnode l1...

leetcode 排序鍊錶

利用歸併排序的思想,不過這裡排序的不是列表,是乙個鍊錶。具體 如下 definition for singly linked list.class listnode object def init self,x self.val x self.next none class solution obj...

LeetCode 排序鍊錶

給你鍊錶的頭結點head,請將其按公升序排列並返回排序後的鍊錶。高階 示例 1 輸入 head 4,2,1,3 輸出 1,2,3,4 示例 2 輸入 head 1,5,3,4,0 輸出 1,0,3,4,5 示例 3 輸入 head 輸出 歸併排序 將鍊錶拆分為二 listnode head1 sor...