Insertion Sort List

来源:互联网 发布:经济学推荐书籍 知乎 编辑:程序博客网 时间:2024/06/16 09:28
------QUESTION------
Sort a linked list using insertion sort.

------SOLUTION------

class Solution {public:    ListNode *insertionSortList(ListNode *head) {        if(!head || !head->next) return head;        ListNode *tail =head->next;        head->next = NULL;        ListNode *current;        ListNode *tmp;                while(tail){            if(tail->val < head->val){                tmp = tail->next;                tail->next = head;                head = tail;                tail = tmp;                continue;            }                         current = head;            while(current->next && tail->val >= current->next-> val)  current = current->next;            tmp = tail->next;            tail->next = current->next;            current->next = tail;            tail = tmp;        }        return head;    }};

0 0
原创粉丝点击