[LeetCode]Insertion Sort List

Sort a linked list using insertion sort.

写个子函数把最后一个节点插入到合适的位置。

注意每次插入后链表值改变了。

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(head == nullptr) return nullptr;
        ListNode * pre = new ListNode(0);
        pre->next = head; //链条的内容随时在改变,写代码时特别注意
        int k = 0;
        while(true){
            ListNode *nex = pre;
            int temp = k;
            while(temp>0){
                nex = nex ->next; //每次遍历,找到最后一个点,注意链表排序后各个点的位置改变了
                --temp;
            }
            k++;
            if(nex->next==nullptr) break;
            else insertList(pre,nex);
        }
        return pre->next;
    }
    void insertList(ListNode* pre,ListNode *front){//在链条中插入最后的一个点
        ListNode* head = pre->next;
        ListNode* last = front->next;
        if(head==last)
            return ;
        while(head!=last){
            if(head->val>last->val){
                pre->next = last;
                front->next = last->next;
                last->next = head;
                break; //找到插入点终止循环
            }
            pre = pre->next;
            head = head->next;
        }
    }
};


你可能感兴趣的:([LeetCode]Insertion Sort List)