leetcode-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
想法:限制了复杂度要求,使用归并排序,找到链表中间,将其断开,然后分别对两个子联表进行排序,最后在合并成一个链表
class Solution {
 public:
     ListNode* sortList(ListNode* head) {
         if (head == NULL || head->next == NULL)  return head;
         ListNode *fast = head, *slow = head;
         while (fast->next != NULL && fast->next->next != NULL)
         {
             fast = fast->next->next;
             slow = slow->next;
         }
         fast = slow;
         slow = slow->next;
         fast->next = NULL;
 
         ListNode *l1 = sortList(head); //前半段排序
         ListNode *l2 = sortList(slow); //后半段排序
         return mTL(l1, l2);
     }

     ListNode *mTL(ListNode *l1, ListNode *l2){
         ListNode haha(-1);
         for (ListNode* p = &haha; l1 != NULL || l2 != NULL; p = p->next)
         {
             int val1 = l1 == NULL ? INT_MAX : l1->val;
             int val2 = l2 == NULL ? INT_MAX : l2->val;
             if (val1 <= val2)
             {
                 p->next = l1;
                 l1 = l1->next;
             }
             else
             {
                 p->next = l2;
                 l2 = l2->next;
             }
         }
         return haha.next;
     }
 };

猜你喜欢

转载自www.cnblogs.com/tingweichen/p/9879298.html