码迷,mamicode.com
首页 > 编程语言 > 详细

147. 对链表进行插入排序

时间:2020-04-03 12:22:52      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:class   null   def   防止   public   else   ret   solution   link   

 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 //1、始终保持pre指向虚拟头结点
10 //2、cur为最后一个节点,即cur->next = NULL
11 class Solution 
12 {
13 public:
14     ListNode* insertionSortList(ListNode* head) 
15     {
16         if(head == NULL || head->next == NULL) return head;
17         ListNode* dummy = new ListNode(-1); 
18         dummy->next = head;
19         
20         ListNode* pre = dummy;
21         ListNode* cur = head;
22 
23         head = head->next;//
24         while(head)
25         {
26             ListNode* h = head->next;//对head->next进行备份,因为后面要进行修改
27             ListNode* temp = pre;//因为始终保持pre指向虚拟头结点,所以防止修改要进行备份
28             for(;temp->next != cur;temp = temp->next)
29             {
30                 if(temp->next->val > head->val)//如果head的值小于temp->next的值,则在head左边进行插入
31                 {
32                     head->next = temp->next;
33                     temp->next = head;
34                     break;
35                 }
36             }
37             if(temp->next == cur)
38             {
39                 if(temp->next->val > head->val)//如果head的值小于temp->next的值,则在head左边进行插入
40                 {  
41                     head->next = cur;
42                     temp->next = head;
43                 }
44                 else //否则在右边进行插入
45                 {
46                     cur->next = head;
47                     cur = cur->next;
48                 }
49             }
50             cur->next = NULL;//始终保持cur为最后一个节点
51             head = h;
52         }
53         return dummy->next;
54     }
55 };

 

147. 对链表进行插入排序

标签:class   null   def   防止   public   else   ret   solution   link   

原文地址:https://www.cnblogs.com/yuhong1103/p/12625416.html

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