1. 程式人生 > >Insertion Sort List —— Leetcode

Insertion Sort List —— Leetcode

Sort a linked list using insertion sort.

連結串列與普通的插入排序最大的區別在於:需記錄插入結點和被插入結點的前驅,以便快速插入。

我的程式碼執行時間不是最快的:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    /**
     * insert 把i插到j後面,pre_i為i的前一個
     * */
    void insert(ListNode* pre_i, ListNode* j) {
        ListNode* i = pre_i->next;
        pre_i->next = i->next;
        i->next = j->next;
        j->next = i;
    }
    
    ListNode* insertionSortList(ListNode* head) {
        if(head==NULL || head->next==NULL)    return head;
        
        ListNode* tmp_head = new ListNode(0);
        tmp_head->next = head;
        for(ListNode* i=head, *pre_i=tmp_head; i != NULL; pre_i = i, i = i->next) {
            ListNode* j = tmp_head; //從tmp_head開始的原因是:後插簡單于前插
            while(j->next != i) {
                if(i->val < j->next->val) { //把i插到j後面,pre_i為i的前一個
                    insert(pre_i, j);
                    i = pre_i;
                }
                else {
                    j = j->next;
                }
            }
        }
        head = tmp_head->next;
        delete tmp_head;
        return head;
    }
};