-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insertion Sort List
51 lines (49 loc) · 1.19 KB
/
Insertion Sort List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
*Sort a linked list using insertion sort
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode *nextnode;
ListNode *p;
ListNode *t;
ListNode *preNode=NULL;
for(p=head;p!=NULL;)
{
nextnode=p->next;
if(nextnode==NULL) break;
for(t=head;t!=nextnode&&nextnode->val > t->val;t=t->next)
{
preNode=t;
}
if(preNode!=NULL){
if(preNode==p)
{
p=p->next;
}
else
{
p->next=nextnode->next;
nextnode->next=preNode->next;
preNode->next=nextnode;
}
}
else
{
p->next=nextnode->next;
nextnode->next=head;
head=nextnode;
}
preNode=NULL;
}
return head;
}
};