LeetCode-M-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) {
        if(head == NULL || head->next == NULL) return head;
        ListNode* tail = head;
        ListNode* next = head->next;
        while(next != NULL){
            ListNode* pre = NULL;
            ListNode* cur = head; 
            while(cur != next && cur->val < next->val){
                pre = cur;
                cur = cur->next;
            }
            if(cur == next) {
                tail = next;
            }else if(pre == NULL){
                tail->next = next->next;
                next->next = head;
                head = next;
            }else{
                tail->next = next->next;
                next->next = pre->next;
                pre->next = next;
            }
            next = tail->next;
        }
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章