LeetCode | 147. Insertion Sort List

 

题目:

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,真的又暖又甜~ 也许不管在什么时候,美好的事物都是那么美好吧~ 加油呀~

 

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页