首页 > 代码库 > 双端链表 冒泡排序

双端链表 冒泡排序

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 typedef char * ElemType;
 6 
 7 typedef struct DuLNode {
 8     ElemType data;
 9     struct DuLNode *prior, *next;
10 } DuLNode, *DuLinkList;
11 
12 
13 DuLinkList create(){
14     return (DuLinkList)malloc(sizeof(DuLNode));
15 }
16 
17 char * create_str(int size){
18     return (char *)malloc((size + 1) * sizeof(char));
19 }
20 
21 void scan(DuLinkList &L){
22     int n;
23     char str[100];
24     DuLinkList lp, p;
25     scanf("%d", &n);
26     scanf("%s", str);
27     p = create();
28     p->data =http://www.mamicode.com/ create_str(strlen(str));
29     strcpy(p->data, str);
30     p->prior = NULL;
31     p->next = NULL;
32     L = p;
33     while(--n){
34         scanf("%s", str);
35 
36         DuLinkList lp;
37         lp = create();
38         lp->data =http://www.mamicode.com/ create_str(strlen(str));
39         strcpy(lp->data, str);
40         lp->prior = p;
41         lp->next = NULL;
42 
43         p->next = lp;
44 
45         p = lp;
46     }
47 }
48 void insertion_sort(DuLinkList &L){
49     
50     DuLinkList sign = NULL, p1, p2;
51     for(DuLinkList cnt = L; cnt->next != NULL; cnt = cnt->next){
52         for(p1 = L, p2 = L->next; p2 != sign; p1 = p1->next, p2 = p2->next){
53             if(strcmp(p1->data, p2->data) >= 0){
54                 char *tmp = p1->data;
55                 p1->data = http://www.mamicode.com/p2->data;
56                 p2->data =http://www.mamicode.com/ tmp;
57             }
58         }
59         sign = p1;
60     }
61 }
62 
63 void print(DuLinkList L){
64     while(L != NULL){
65         printf("%s ", L->data);
66         L = L->next;
67     }
68     puts("");
69 }
70 
71 int main(){
72     //freopen("data.txt", "r", stdin);
73     DuLinkList L;
74     //输入数据
75     scan(L);
76     //打印输出
77     print(L);
78     //冒泡排序
79     insertion_sort(L);
80     //打印数据
81     print(L);
82 
83     return 0;
84 }

测试数据

10
9只小昆虫
8只小昆虫
7只小昆虫
6只小昆虫
5只小昆虫
4只小昆虫
3只小昆虫
2只小昆虫
1只小昆虫
0只小昆虫

 

双端链表 冒泡排序