insertion-sort-list leetcode C++

Sort a linked list using insertion sort.

C++

/**
 * 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* newHead = new ListNode(-1);
        while (NULL != head){
            ListNode* tmp = head->next;
            ListNode* cur = newHead;
            while(cur->next != NULL && cur->next->val < head->val){
                cur = cur->next;
            }
            head->next = cur->next;
            cur->next = head;
            head = tmp;
        }
        return newHead->next;
    }
};

 

posted @ 2018-09-22 10:57  vercont  阅读(157)  评论(0编辑  收藏  举报