LeetCode 147. Insertion Sort List

Posted 皇家大鹏鹏

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 147. Insertion Sort List相关的知识,希望对你有一定的参考价值。

Sort a linked list using insertion sort.

 

讲真,很久没做这么累的链表题目了,这道题折腾了我很久,说实话,最后改来改去,自己还是一知半解,这道题折腾了我一天多,实在是累。实在是搞不懂出这道题的人脑子里面究竟在想什么,注意一个问题,这道题和之前链表题目的不同之处在于它不能在一开始就把虚拟头结点连在连表情前面,否则会报错,参考代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* insertionSortList(ListNode* head) {
12         if (!head || !head->next)
13             return head;
14         ListNode *dummy = new ListNode(-1);
15        // dummy->next = head;
16         ListNode *cur = head, *pre = dummy;  //这里pre应当指向dummy而非head
17         //ListNode *tmp = nullptr;
18         while (cur)
19         {
20             ListNode *tmp = cur->next;
21             while (pre->next && pre->next->val < cur->val)
22                 pre = pre->next;
23             cur->next = pre->next;  //这里链表会产生断裂,但是没关系,我们之前已经保留下来
24             pre->next = cur;
25             cur = tmp;
26             pre = dummy;
27         }
28         return dummy->next;
29     }
30 };

这是另一位大神的解法,供参考:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *insertionSortList(ListNode *head) {
12         ListNode *res = new ListNode(-1);
13         ListNode *cur = res;
14         while (head) {
15             ListNode *next = head->next;
16             cur = res;
17             while (cur->next && cur->next->val <= head->val) {
18                 cur = cur->next;
19             }
20             head->next = cur->next;
21             cur->next = head;
22             head = next;
23         }
24         return res->next;
25     }
26 };

 

以上是关于LeetCode 147. Insertion Sort List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-147-Insertion Sort List

LeetCode 147. Insertion Sort List

Leetcode 147. Insertion Sort List 插入排序 in Java

leetcode 147 Insertion Sort List

Leetcode147. Insertion Sort List

LeetCode 147. Insertion Sort List