关于单链表的一些操作

RT:

View Code
1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4 #include <cstdlib>
5 #include <conio.h>
6
7  using namespace std;
8
9 typedef struct student
10 {
11 int data;
12 struct student *next;
13 }node;
14
15  /* 实现一个单链表的创建 */
16 node* ListCreate()
17 {
18 node *head,*p,*tmp;
19 int x,cycle = 1;
20 head =(node*)malloc(sizeof(node));
21 p = head;
22 while(cycle)
23 {
24 printf("\nplease input the data:");
25 scanf("%d",&x);
26 if(x != 0)
27 {
28 tmp = (node*)malloc(sizeof(node));
29 tmp->data = x;
30 p->next = tmp;
31 p = tmp;
32 }else cycle = 0;
33 }
34 head = head->next;
35 p->next = NULL;
36 return(head);
37 }
38
39 /* 实现单链表的测长 */
40 int ListLen(node *head)
41 {
42 int n = 0;
43 node *p;
44 p = head;
45 while(p != NULL)
46 {
47 p = p->next;
48 n++;
49 }
50 return(n);
51 }
52
53 /* 实现单链表的打印 */
54 void ListPrint(node *head)
55 {
56 node *p;
57 int n;
58 n = ListLen(head);
59 printf("\nNow,There %d records are:\n",n);
60 p = head;
61 while(p)
62 {
63 printf("\n %d ",p->data);
64 p = p->next;
65 }
66 }
67
68 /* 单链表选择排序 */
69 node* SelectSort(node* head)
70 {
71 node *first,*tail,*p,*min,*p_min;
72 first = NULL;
73 while(head != NULL)
74 {
75 for(p = head,min = head;p->next != NULL;p = p->next)
76 {
77 if(p->next->data < min->data)
78 {
79 min = p->next;
80 p_min = p;
81 }
82 }
83
84 if(first == NULL)
85 {
86 first = min;
87 tail = min;
88 }else{
89 tail->next = min;
90 tail = min;
91 }
92
93 if(min == head)
94 head = head->next;
95 else
96 p_min->next = min->next;
97 }
98 if(first != NULL)
99 tail->next = NULL;
100 head = first;
101 return(head);
102 }
103
104 /* 直接插入排序 */
105 node* InsertSort(node*head)
106 {
107 node *first,*t,*p,*q;
108 first = head->next;
109 head->next = NULL;
110 while(first)
111 {
112 for(t = first,q = head;((q != NULL)&&q->data < t->data);p = q,q = q->next);
113 first = first->next;
114 if(q == head)
115 {
116 head = t;
117 }else
118 {
119 p->next = t;
120 }
121 t->next = q;
122 }
123 return(head);
124 }
125
126
127 /* 冒泡排序 : 只交换节点数据,不知道怎么交换节点*/
128 node* BubbleSort(node* head)
129 {
130 node *p;
131 int n,tmp;
132 n = ListLen(head);
133 printf("\n length=%d\n",n);
134 if(head == NULL || head->next == NULL)
135 return head;
136 for(int j = 1;j < n;++j)
137 {
138 p = head;
139 for(int i = 1;i <= n-j; ++i)
140 {
141 if(p->data > p->next->data)
142 {
143 tmp = p->data;
144 p->data = p->next->data;
145 p->next->data = tmp;
146 }
147 p = p->next;
148 }
149 printf("\n nnn %d",p->data);
150 }
151 return head;
152 }
153
154 int main(void)
155 {
156 node *L;
157 L = ListCreate();
158 ListPrint(L);
159 L = BubbleSort(L);
160 ListPrint(L);
161 return 0;
162 }
posted @ 2011-05-05 12:29  elwin  阅读(137)  评论(0)    收藏  举报