首页 > 其他 > 详细

LeetCode – Refresh – Insertion Sort List

时间:2015-03-20 06:54:23      阅读:295      评论:0      收藏:0      [点我收藏+]

Do not forget to break the inner loop, when you find the insert position.

 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) return head;
13         ListNode *result = new ListNode(0);
14         ListNode *old = new ListNode(0);
15         old->next = head;
16         while (old->next) {
17             ListNode *tmp = old->next, *runner = result;
18             old->next = tmp->next;
19             while (runner) {
20                 if (!runner->next || tmp->val < runner->next->val) {
21                     tmp->next = runner->next;
22                     runner->next = tmp;
23                     break;
24                 }
25                 runner = runner->next;
26             }
27         }
28         return result->next;
29     }
30 };

 

LeetCode – Refresh – Insertion Sort List

原文:http://www.cnblogs.com/shuashuashua/p/4352610.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!