Leetcode148 排序链表(大白话说思路)——链表专题

思路:找中点,用递归不断分割,然后使用合并有序链表的方法合并左右链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:

    ListNode* sortList(ListNode* head) {
        //找中点,不断分割数据,合并
        return mergeList(head);
    }


    ListNode*mergeList(ListNode*&head){
        //找中点不断分割
        if(head==NULL||head->next==NULL){
            return head;
        }
        ListNode*slow = head;
        ListNode*fast = head;
        ListNode*pre = NULL;
        while(fast&&fast->next){
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
        ListNode*L = mergeList(slow);
        ListNode*R  = mergeList(head);
        return merge(L,R);
    }

    ListNode*merge(ListNode*L,ListNode*R){
        ListNode*dummy = new ListNode(-1);
        auto pre = dummy;
        while(L&&R){
            if(L->val<=R->val){
                pre->next =L;
                pre = pre->next;
                L = L->next;
            }
            else{
                pre->next = R;
                pre = pre->next;
                R = R->next;
            }
        }
        pre->next = L?L:R;
        return dummy->next;
    }
};

插入排序,从第二个节点开始,插到前面已排好序的链表应该在的位置

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) { 
        ListNode*dummy  = new ListNode(-1);
        dummy->next = head;
        auto tail = head;
        auto cur = head->next;
        while(cur){
            ListNode*nex = cur->next;
            if(tail->val<=cur->val){
            	//更新尾部节点
                tail = tail->next;
            }
            else{
            	//从前往后找 注意更新尾部节点
                ListNode*p = dummy;
                ListNode*q = dummy->next;
                while(q->val<=cur->val){
                    p = p->next;
                    q = q->next;
                }
                tail->next = cur->next;
                cur->next =q;
                p->next =cur;
            }
            cur = nex;
        }
        return dummy->next;
    }
};

你可能感兴趣的:(面试,链表,list,leetcode)