题目描述

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。要求常数空间,时间复杂度为O(nlogn)
链接:https://leetcode-cn.com/problems/sort-list/

解题思路

采用归并排序:

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. ListNode* middleNode(ListNode* head) {
  14. // 确保链表至少有两个节点
  15. ListNode* fast = head;
  16. ListNode* slow = new ListNode();
  17. slow->next = head;
  18. while (fast && fast->next) {
  19. slow = slow->next;
  20. fast = fast->next->next;
  21. }
  22. return slow;
  23. }
  24. ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
  25. if(l1==NULL)
  26. return l2;
  27. if(l2==NULL)
  28. return l1;
  29. if(l1->val < l2->val){
  30. l1->next = mergeTwoLists(l1->next,l2);
  31. return l1;
  32. }else{
  33. l2->next = mergeTwoLists(l1,l2->next);
  34. return l2;
  35. }
  36. }
  37. ListNode* sortList(ListNode* head) {
  38. if (head==NULL || head->next==NULL) {
  39. return head;
  40. }
  41. ListNode* mid_node = middleNode(head);
  42. ListNode* right_node = mid_node->next;
  43. mid_node->next = NULL;
  44. ListNode* left = sortList(head);
  45. ListNode* right = sortList(right_node);
  46. return mergeTwoLists(left, right);
  47. }
  48. };