/*
實現單鏈表的基本功能:
1. 利用scanf輸入5個學生信息并打印
2. 在第i個學生前面插入一個新的學生
3. 刪除第i個學生
*/
#include<stdio.h>
#include<stdlib.h>
typedef?struct?student{
int?num;
int?phone;
char?name[10];
struct?student?*next;
}struct_t;
int?main(){
int?i=1,m,n;
struct_t?*p1;
struct_t?*p2;
struct_t?*p3;
struct_t?*p4;
struct_t?*p5;
struct_t?*p6;
printf("請輸入5個學生的信息:\n");
p5=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p5->name,&p5->num,&p5->phone);
p5->next=NULL;
p4=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p4->name,&p4->num,&p4->phone);
p4->next=p5;
p3=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p3->name,&p3->num,&p3->phone);
p3->next=p4;
p2=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p2->name,&p2->num,&p2->phone);
p2->next=p3;
p1=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p1->name,&p1->num,&p1->phone);
p1->next=p2;
struct_t?*p=p1;
printf("序號\t姓名\t學號\t電話號碼\n");//輸入5個學生信息后,輸出學生的信息
while(p?!=?NULL){
printf("%d\t%s\t%d\t%d\n",i,p->name,p->num,p->phone);
p?=?p->next;
i++;
}
//插入信息
printf("在第幾位學生前添加信息?\n");
scanf("%d",&m);
printf("請輸入信息:\n");
switch(m){
case?1:{
p6=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p6->name,&p6->num,&p6->phone);
p6->next=p1;
???}break;
case?2:{
p6=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p6->name,&p6->num,&p6->phone);
p1->next=p6;
p6->next=p2;
???}break;
case?3:{
p6=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p6->name,&p6->num,&p6->phone);
p2->next=p6;
p6->next=p3;
???}break;
case?4:{
p6=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p6->name,&p6->num,&p6->phone);
p3->next=p6;
p6->next=p4;
???}break;
case?5:{
p6=(struct_t?*)malloc(sizeof(struct_t));
scanf("%s%d%d",p6->name,&p6->num,&p6->phone);
p4->next=p6;
p6->next=p5;
???}break;
default :printf("無此學生\n");break;
}
if(m?!=?1)
struct_t?*p=p1;
else
struct_t?*p=p6;
i=1;
printf("序號\t姓名\t學號\t電話號碼\n");//插入1位學生的信息后,輸出學生的信息
while(p?!=?NULL){
printf("%d\t%s\t%d\t%d\n",i,p->name,p->num,p->phone);
p?=?p->next;
i++;
}
//刪除信息
p=p1;
printf("刪除第幾位學生的信息?\n");
scanf("%d",&n);
switch(n){
case?1:{
p1->next=NULL;p=p2;
break;
???}
case?2:{
p1->next=p3;p=p1;
break;
???}
case?3:{
p2->next=p4;p=p1;
break;
???}
case?4:{
p3->next=p5;p=p1;
break;
???}
case?5:{
p4->next=p6;p=p1;
break;
???}
case?6:{
p5->next=NULL;p=p1;
break;
???}
default :printf("無此學生\n");break;
}
?????i=1;
printf("序號\t姓名\t學號\t電話號碼\n");//刪除1位學生的信息后,輸出學生的信息
while(p?!=?NULL){
printf("%d\t%s\t%d\t%d\n",i,p->name,p->num,p->phone);
p?=?p->next;
i++;
}
free(p1);
free(p2);
free(p3);
free(p4);
free(p5);
free(p6);
return?0;
}
添加回答
舉報
0/150
提交
取消