码迷,mamicode.com
首页 > 编程语言 > 详细

链表的排序(归并排序+快慢指针)

时间:2020-04-06 17:33:04      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:size   turn   slow   快慢指针   family   tno   归并   过程   amp   

链表的排序有很多方式,这里记录一下归并排序,关键点2个: 归并排序的过程和快慢指针法找中间结点,直接上代码。 

class Solution {
public:
         ListNode* sortList(ListNode* head) {
                if (!head || !head->next) return head;
                ListNode* slow = head, * fast = head->next;
                while (fast && fast->next) {
                        slow = slow->next;
                        fast = fast->next->next;
                }
                ListNode* left = sortList(slow->next); // slow 为中间结点了
                slow->next = NULL;
                ListNode* right = sortList(head);
                return merge(left, right);
         }
         ListNode* merge(ListNode* left, ListNode* right) {
                ListNode* dummy = new ListNode(0);
                ListNode* p = dummy;
                while (left && right) {
                        if (left->val < right->val) {
                               p->next = left;
                               left = left->next;
                        }
                        else {
                               p->next = right;
                               right = right->next;
                        }
                        p = p->next;
                }
                if (left) p->next = left;
                if (right) p->next = right;
                return dummy->next;
         }
};

  

 

链表的排序(归并排序+快慢指针)

标签:size   turn   slow   快慢指针   family   tno   归并   过程   amp   

原文地址:https://www.cnblogs.com/E-Dreamer-Blogs/p/12642805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!