147. Insertion Sort List

来源:互联网 发布:地铁刷卡数据存闸机 编辑:程序博客网 时间:2024/06/05 16:36

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:    ListNode* insertionSortList(ListNode* head) {        vector<ListNode*> vec;        if(head == NULL || head->next == NULL) return head;        vec.push_back(head);        ListNode* tmp = head->next;        for( ; tmp != NULL; tmp = tmp->next){            int size = vec.size();            vec.push_back(tmp);            for(int i = size - 1; i >= 0; i--){                if(vec[i]->val > vec[i + 1]->val){                    if(i == 0) {                        ListNode* tnext = vec[1]->next;                        vec[1]->next = vec[0];                        vec[0]->next = tnext;                    } else {                        ListNode* pre = vec[i - 1];                        pre->next = vec[i + 1];                        vec[i]->next = vec[i + 1]->next;                        vec[i + 1]->next = vec[i];                    }                    swap(vec[i], vec[i + 1]);                                }            }            tmp = vec[size];        }        return vec[0];    }};

参考discuss:https://discuss.leetcode.com/topic/8570/an-easy-and-clear-way-to-sort-o-1-space

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* insertionSortList(ListNode* head) {        if(head == NULL || head->next == NULL) return head;        ListNode* helper = new ListNode(0);        ListNode* cur = head;        ListNode* pre = helper;        ListNode* next = NULL;        while(cur != NULL){            next = cur->next;            while(pre->next != NULL && pre->next->val < cur->val)                pre = pre->next;            cur->next = pre->next;            pre->next = cur;            pre = helper;            cur = next;        }        return helper->next;    }};
原创粉丝点击