148. 排序链表

题目描述

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

思路

对于链表的归并排序,不需要额外的辅助空间(链表通过指针达到逻辑上相邻,而不像数组是物理上相邻,所以针对两个有序链表的合并可以只改动指针,原地进行),这一点不像数组,因为我们可以就地合并两个有序的链表,这一点对于排序两个有序的数组则需要一个辅助的数组来存放结果。

代码实现

class Solution {
public:
    ListNode *merge(ListNode *l1, ListNode *l2) {  	                                        
    	if(l1 == nullptr)
    		return l2;
    	if(l2 == nullptr)
    		return l1;    	
        ListNode *dummy = new ListNode(-1);
        ListNode *p1 = l1;
        ListNode *p2 = l2;
        ListNode *last = dummy;
        while(p1!=nullptr && p2!=nullptr) 
        {
            if(p1->val <= p2->val)//这里必须是<=,因为归并排序是稳定的排序算法 
            {
            	last->next = p1;
                p1 = p1->next;
                last = last->next;
                last->next = nullptr;
                
            } 
            else 
            {
            	last->next = p2;
                p2 = p2->next;
            	last = last->next;
                last->next = nullptr;
                
            }
        }         
        if (p1 != nullptr)
            last->next = p1;
        if (p2 != nullptr)
            last->next = p2;
        ListNode *ret = dummy->next;
        dummy->next = nullptr;
        delete dummy;                
        return ret;
        
    }
    ListNode *sortList(ListNode *head)//主函数
    {
        if(head==nullptr || (head->next)==nullptr)
        	return head;//递归终止条件
        ListNode *fast=head;
        ListNode *slow=head;
        //快指针还能不能再走两步?
        while(fast->next && fast->next->next)//循环条件为针对快指针的操作还能不能继续进行?
        {
            slow = slow->next;
            fast = fast->next->next;
        }//循环结束后慢指针已经到达正确的位置了,
        fast = slow->next;//得出的slow为分割点
        slow->next = nullptr;
        slow = head;
        ListNode *l1 = sortList(slow);
        ListNode *l2 = sortList(fast);
        return merge(l1,l2);
    }
};

posted on 2021-05-16 14:27  朴素贝叶斯  阅读(42)  评论(0编辑  收藏  举报

导航