首页 > 其他 > 详细

leetcode Insertion Sort List

时间:2014-09-24 01:05:26      阅读:289      评论:0      收藏:0      [点我收藏+]

题目: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     
13         
14     if (head==NULL||head->next==NULL)//only 0,1nodes
15     {
16         return    head;
17     }
18 
19     ListNode    *pNode=head->next,*hNode=head,*tNode=NULL;
20     hNode->next=NULL;
21     while(pNode)
22     {
23         hNode=head;
24 
25     
26 
27       // find where to insert
28       while (hNode)
29       {
30           if (hNode->val>pNode->val)//插入头结点之前
31           {
32               tNode=pNode->next;
33               pNode->next=hNode;
34               head=pNode;
35               hNode=head;
36               pNode=tNode;
37               break;
38           }
39           else if (hNode->next==NULL)//到了最后一个节点
40           {
41               tNode=pNode->next;
42               hNode->next=pNode;
43               pNode->next=NULL;
44               pNode=tNode;
45               break;
46           }
47           else if (hNode->next->val>pNode->val)
48           {
49               tNode=pNode->next;
50               pNode->next=hNode->next;
51               hNode->next=pNode;
52               pNode=tNode;
53               break;
54           }
55           else
56           {
57               hNode=hNode->next;
58           }
59         
60       }
61 
62     }
63     
64     return head;
65     }
66 };

 

 

leetcode Insertion Sort List

原文:http://www.cnblogs.com/karcylee/p/3989607.html

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