學渣帶你刷Leetcode147. 對鏈表進行插入排序

題目描述

示例 1:

輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:

輸入: -1->5->3->4->0
輸出: -1->0->3->4->5

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/insertion-sort-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

白話題目:
 

算法:

 

詳細解釋關注 B站  【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB

C語言完全代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* insertionSortList(struct ListNode* head){
    if(head == NULL || head->next == NULL)
        return head;

    struct ListNode dummy, *cur, *pre;
    dummy.next = head;
    cur = head->next;
    pre = head;
    while(cur)
    {
        if(cur->val < pre->val) /* 當前節點比上一個節點大,需要調整*/
        {
            struct ListNode *sort_cur = &dummy;
            for(; sort_cur->next->val < cur->val; sort_cur = sort_cur->next);/*從頭開始找到第一個比當前節點大的節點,最差情況下找到上一個節點*/
            pre->next = cur->next; /*更新上一個節點的下一個指針*/
            cur->next = sort_cur->next;
            sort_cur->next = cur;
            cur = pre->next;

        }
        else /* 當前節點小於等於上一個節點,不需要調整*/
        {
            pre = cur;
            cur = cur->next;
        }
    }
    return dummy.next;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章