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 };

自己后来又想了一下,这道题并不难,数组中的插入排序是从后往前移动元素,而链表中的插入排序则是调整指针的移动方向,关于上面的代码,我觉得可以这么解释,请看下图,我们执行的过程就是把右边的原先链表中的节点逐个插入到左边的新的链表中。做链表的题目首先需要搞清楚场景,什么时候需要加入虚拟头结点来避免引入二重指针,还有就是while和if的条件中何时需要判断next以及next的next是否为空,这都是细节问题,也可以说是最容易出错的地方

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

 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 };
原文地址:https://www.cnblogs.com/dapeng-bupt/p/8309274.html