Insertion Sort List

来源:互联网 发布:淘宝开店要注册商标吗 编辑:程序博客网 时间:2024/06/03 14:34

Sort a linked list using insertion sort.


Solution:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* insertNode(ListNode* head, int val)    {        ListNode *pre = NULL, *cur = head;        while(cur && val >= cur->val)        {            pre = cur;            cur = cur->next;        }        ListNode* x = new ListNode(val);        if(!pre)        {            head = x;            x->next = cur;        }        else        {            pre->next = x;            x->next = cur;        }        return head;    }    ListNode* insertionSortList(ListNode* head) {        ListNode* res = NULL;        while(head)        {            res = insertNode(res, head->val);            head = head->next;        }        return res;    }};


0 0