LeetCode 148. Sort List C++

148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

Approach

  1. 将链表排序,时间复杂度保持在nlog(n)内,这个时间复杂度的排序,一般就是快排、归并等,然后对于链表来说,归并无疑是最合适的,所以这里也采用归并排序,思路都一样,主要看写法,该怎么写,这比较主要。

Code

class Solution {
 public:
     ListNode* merge(ListNode* left1, ListNode* left2) {
         ListNode *p = new ListNode(0) *cur = p;
         while (left1&&left2) {
             if (left1->val < left2->val) {
                 p->next = left1;
                 left1 = left1->next;
             }
             else {
                 p->next = left2;
                 left2 = left2->next;
             }
             p = p->next;
         }
         p->next = left1 ? left1 : left2;
         return cur->next;
     }
     ListNode* sortList(ListNode* head) {
         if (!head || !head->next)return head;
         ListNode *slow = head, *fast = head, *pre = head;
         while (fast&&fast->next) {
             pre = slow;
             slow = slow->next;
             fast = fast->next->next;
         }
         pre->next = nullptr;
         return merge(sortList(head), sortList(slow));
     }
 };

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/82013099