[leetcode] 147. Insertion Sort List

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


发布了31 篇原创文章 · 获赞 0 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章