[关闭]
@snuffles 2019-04-10T18:19:05.000000Z 字数 968 阅读 785

L148 排序链表

链表


在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。示例 1:
输入: 4->2->1->3
输出: 1->2->3->4

解:O(NLOGN)的排序方法包括,快排,归并,堆。根据单链表的特点,最适合用于归并排序。

  1. //归并排序
  2. ListNode* sortList(ListNode* head) {
  3. // special case
  4. if(!head || !head->next) return head;
  5. ListNode *slow = head,*fast= head, *cur = head;
  6. // find the middle of the link
  7. while(fast && fast->next){
  8. cur = slow;
  9. slow = slow->next;
  10. fast = fast -> next ->next;
  11. }
  12. cur->next = NULL;
  13. return merge(sortList(head),sortList(slow));
  14. }
  15. ListNode* merge(ListNode *l1, ListNode *l2){
  16. ListNode *dummy = new ListNode(-1);
  17. ListNode *cur = dummy;
  18. while(l1 && l2){
  19. if(l1->val < l2->val){
  20. cur->next = l1;
  21. l1 = l1->next;
  22. }else{
  23. cur->next = l2;
  24. l2 = l2->next;
  25. }
  26. cur = cur->next;
  27. }
  28. cur->next = l1?l1:l2;
  29. return dummy->next;
  30. }
  31. //作弊sort
  32. ListNode* sortList(ListNode* head) {
  33. if(head==NULL) return head;
  34. vector<int> res;
  35. ListNode *newhead=head;
  36. while(head->next!=NULL){
  37. res.push_back(head->val);
  38. head=head->next;
  39. }
  40. res.push_back(head->val);
  41. sort(res.begin(),res.end());
  42. head = newhead;
  43. int i=0;
  44. while(head->next!=NULL){
  45. head->val=res[i];
  46. head=head->next;
  47. i++;
  48. }
  49. head->val=res[i];
  50. return newhead;
  51. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注