147. Insertion Sort List

来源:互联网 发布:java招聘系统源码 编辑:程序博客网 时间:2024/06/08 04:15

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) {        ListNode* new_head = new ListNode(0);        new_head -> next = head;        ListNode* pre = new_head;        ListNode* cur = head;        while (cur) {            if (cur -> next && cur -> next -> val < cur -> val) {                while (pre -> next && pre -> next -> val < cur -> next -> val)                    pre = pre -> next;                /* Insert cur -> next after pre.*/                ListNode* temp = pre -> next;                pre -> next = cur -> next;                cur -> next = cur -> next -> next;                pre -> next -> next = temp;                /* Move pre back to new_head. */                pre = new_head;            }            else cur = cur -> next;        }        ListNode* res = new_head -> next;        delete new_head;        return res;    }};