單鏈表的創(chuàng)建、計數打印、刪除與插入操作,提供四輪刪除與插入操作,gcc編譯通過。
1 #include<stdio.h>
2 #include<stdlib.h> /*使用到其中的malloc和exit函數*/
3 #define times 4 /*用于循環(huán)次數的控制*/
4
5 static int N=4; /*靜態(tài)全局變量,用于控制單鏈表長度*/
6
7 typedef struct _person
8 {
9 char name[12];
10 int age;
11 struct _person *next;
12 }stud;
13
14 stud *Create(int num) /*創(chuàng)建單鏈表的函數,num為單鏈表的長度*/
15 {
16 int i;
17 stud *h,*p,*q; /* h為頭指針,指向單鏈表的第一個節(jié)點*/
18 h=(stud*)malloc(sizeof(stud));
19 if(h!=NULL)
20 {
21 p=h;
22 for(i=0;i<num;i++)
23 {
24 q=(stud*)malloc(sizeof(stud)); /* q為指向新建節(jié)點的指針*/
25 if(q!=NULL)
26 {
27 printf("依次輸入第%d個人的姓名和年齡:\n",i+1);
28 scanf("%s%d",q->name,&q->age);
29 q->next=NULL; /*創(chuàng)建新節(jié)點完畢*/
30 p->next=q;
31 p=q;
32 }
33 }
34 }
35 printf("\n");
36 return(h);
37 }
38
39 stud *Delete(stud *person,int post) /*刪除單鏈表指定位置節(jié)點的函數*/
40 {
41 int i;
42 stud *cur,*pre;
43 cur=person;
44
45 if(0==post) /*如果輸入的值為0,則不刪除任何節(jié)點*/
46 {
47 printf("\n注意:您決定不刪除任何節(jié)點!!!\n\n");
48 return(person);
49 }
50 else if(post>N||post<0) /*如果輸入的值大于單鏈表長度或者小于0,程序結束*/
51 {
52 printf("輸入有誤,程序終止。\n");
53 exit(1);
54 }
55 else
56 {
57 if(1==post) /*在單鏈表頭部刪除的情況*/
58 {
59 cur=cur->next;
60 person->next=cur->next;
61 free(cur);
62 }
63 else /*在其它位置刪除的情況*/
64 {
65 for(i=2;i<post+1;i++) /*使pre成為要插入位置的上一位置的節(jié)點*/
66 {
67 cur=cur->next;
68 pre=cur;
69 }
70 cur=cur->next;
71 pre->next=cur->next;
72 free(cur);
73 }
74 return(person);
75 }
76 }
77
78 stud *Insert(stud *person,int post) /*在單鏈表指定位置插入新的節(jié)點的函數*/
79 {
80 int i;
81 stud *cur,*pre,*node;
82
83 if(post>N+1||post<1) /*如果輸入的值大于單鏈表長度加1或者小于1,程序結束*/
84 {
85 printf("輸入錯誤,程序終止。\n");
86 exit(1);
87 }
88
89 if(person!=NULL)
90 {
91 cur=person;
92 node=(stud*)malloc(sizeof(stud));
93 if(node!=NULL)
94 {
95 printf("請輸入新人的姓名和年齡:\n");
96 scanf("%s%d",node->name,&node->age); /*為新的節(jié)點輸入數據內容*/
97
98 if(1==post)
99 {
100 node->next=person->next;
101 person->next=node;
102 }
103 else
104 {
105 for(i=2;i<post+2;i++)
106 {
107 pre=cur;
108 cur=cur->next;
109 }
110 node->next=pre->next;
111 pre->next=node;
112 }
113 }
114 }
115 printf("\n");
116 return(person);
117 }
118
119 void Print(stud *person)
120 {
121 int post=1;
122 stud *cur;
123 cur=person->next;
124 printf("當前的節(jié)點信息如下所示:\n");
125 while(cur!=NULL)
126 {
127 printf("第%d個人的姓名是:%s,年齡為:%d\n",post,cur->name,cur->age);
128 cur=cur->next;
129 post++;
130 }
131 N=--post;
132 printf("當前單鏈表的長度是:%d\n\n",N);
133 }
134
135 int main()
136 {
137 int number,post,i;
138 stud *head;
139 head=Create(N);
140 Print(head);
141
142 for(i=0;i<times;i++)
143 {
144 printf("請輸入要刪除的節(jié)點的位置:\n");
145 scanf("%d",&number);
146 Delete(head,number);
147 Print(head);
148
149 printf("請輸入要插入節(jié)點的位置(此位置是指預期插入成功后新節(jié)點在單鏈表中的位置):\n");
150 scanf("%d",&post);
151 Insert(head,post);
152 Print(head);
153
154 printf("\n注意:剩余輸入輪數為:%d !!!!!\n\n",(times-(i+1)));
155 }
156
157 return 0;
158 }
調試環(huán)境:Ubuntu Desktop 8.04.4 VIM 7.1.138 GCC 4.2.4QQ:81064483E-mail:AllenNewOK@126.com不足之處,敬請指正。< ^_^ >