1 #include <iostream>
2 using namespace std;
3
4 struct node {
5 int value;
6 node* next;
7 };
8
9 void Insert(node*& head, int data)
10 {
11 node* save = new node;
12 save->next = head;
13 save->value = data;
14 head = save;
15 }
16
17 node* ListInsertSort(node* head)
18 {
19 if (NULL == head || NULL == head->next)
20 return head;
21 node *cur, *nex, *pre, *save;
22 cur = head->next;
23 head->next = NULL;
24 while ( cur ) {
25 save = cur->next;
26 if ( cur->value > head->value ) // 从头部插入
27 {
28 cur->next = head;
29 head = cur;
30 cur = save;
31 }
32 else // 从中间插入
33 {
34 pre = head;
35 nex = head->next;
36 while ( nex && nex->value > cur->value ) // 找到合适的插入位置
37 {
38 pre = nex;
39 nex = nex->next;
40 }
41 pre->next = cur;
42 cur->next = nex;
43 cur = save;
44 }
45 }
46 return head;
47 }
48
49 int main(void)
50 {
51 node* head = NULL;
52 node* nex = NULL;
53 int i;
54 int num[] = {1, 3, 7, 2, 8, 4};
55 for ( i = 0; i < 6; ++i )
56 Insert(head, num[i]);
57 head = ListInsertSort(head);
58 for ( nex = head; nex != NULL; nex = nex->next )
59 cout<<nex->value<<" ";
60 cout<<endl;
61 return 0;
62 }
http://codepad.org/srQBBC1V