码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 147. Insertion Sort List

时间:2018-01-18 13:33:34      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:efi   body   ret   注意   nbsp   nullptr   lin   头结点   node   

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

标签:efi   body   ret   注意   nbsp   nullptr   lin   头结点   node   

原文地址:https://www.cnblogs.com/dapeng-bupt/p/8309274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!