LeetCode: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         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if(head == NULL || head->next == NULL)return head;
15         ListNode *p = head->next, *pstart = new ListNode(0), *pend = head;
16         pstart->next = head; //為了操作方便,添加一個頭結點
17         while(p != NULL)
18         {
19             ListNode *tmp = pstart->next, *pre = pstart;
20             while(tmp != p && p->val >= tmp->val)
21                 {tmp = tmp->next; pre = pre->next;}
22             if(tmp == p)pend = p;
23             else
24             {
25                 pend->next = p->next;
26                 p->next = tmp;
27                 pre->next = p;
28             }
29             p = pend->next;
30         }
31         head = pstart->next;
32         delete pstart;
33         return head;
34     }
35 };

【版權聲明】轉載請注明出處:http://www.cnblogs.com/TenosDoIt/p/3422296.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM