糖逗 发表于 2020-8-1 20:03:17

C++刷LeetCode(148. 排序链表)【归并排序】

题目描述:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
* Definition for singly-linked list.
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
    ListNode* merge(ListNode* head1, ListNode* head2){//递归
      if(head1 == NULL)return head2;
      if(head2 == NULL)return head1;
      if(head1 -> val < head2 -> val){
            head1 -> next = merge(head1 -> next, head2);
            return head1;
      }else{
            head2 -> next = merge(head1, head2 -> next);
            return head2;
      }
    }
    ListNode* sortList(ListNode* head) {//递归
      if(head == NULL || head -> next == NULL)return head;
      ListNode* pre = head, *slow = head, *fast = head;
      while(fast && fast -> next){
            pre = slow;
            slow = slow -> next;
            fast = fast -> next -> next;
      }//这样切出的slow会多出一个,因此要用pre
      pre -> next = NULL;
      return merge(sortList(head), sortList(slow));
    }
};


参考链接:https://leetcode-cn.com/problems/sort-list/solution/lioney-cgui-bing-pai-xu-lian-biao-by-lioney/
页: [1]
查看完整版本: C++刷LeetCode(148. 排序链表)【归并排序】