[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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章