LeetCode | 147. Insertion Sort List

1LOVESJohnny發表於2020-09-30

 

題目:

Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
 

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.


Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

 

程式碼:

/**
 * 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 *new_head = NULL, *p = head, *cur, *q;
        while(p != NULL)
        {
            cur = p;
            p = p->next;
            if(new_head == NULL)
            {
                new_head = cur;
                cur->next = NULL;
            }
            else
            {
                ListNode *pre = NULL;
                for(q = new_head; q != NULL; q = q->next)
                {
                    if(cur->val < q->val)
                    {
                        if(pre == NULL)
                        {
                            cur->next = q;
                            new_head = cur;
                        }
                        else
                        {
                            pre->next = cur;
                            cur->next = q;
                        }
                        break;
                    }
                    pre = q;
                }
                if(q == NULL)
                {
                    pre->next = cur;
                    cur->next = NULL;
                }
            }
        }
        return new_head;
    }
};

 

題外話:

轉眼又到了月底。日子一天天的翻過,如白駒過隙,時間真的好快啊。

還記得年初的時候,三月底的時候感嘆一年的四分之一就飛快過去,轉眼間今年已經過了四分之三,還有四分之一。

在家工作已經到了非常熟悉又開始質變的時候,需要做一些時間管理上的調整。

希望之後可以慢慢實行~

這個月的感慨很簡單,希望大家平平安安,健健康康就好~

願一切都好。

再見,九月;

你好,十月。

 

P.S. 感謝遇到了成交cp,真的又暖又甜~ 也許不管在什麼時候,美好的事物都是那麼美好吧~ 加油呀~

 

 

相關文章