📄 链表中的删除操作.txt
字号:
#define LEN sizeof(struct Node)
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct Record //创建一个结构体
{
char No[6];
char Name[8];
char Sex; //m:男 f:女
int Age;
};
struct Node
{
struct Record Member;
struct Node *next;
};
/*创建链表*/
struct Node *create()
{
struct Node *head,*p,*q;
char ino[6],iname[8],isex;
int iage;
head=NULL;
printf("\n请输入学生的信息\n\n学号\t姓名\t性别\t年龄\n\n");
while(1)
{
scanf("%s",ino);//输入学号
getchar();//读取字符
if(strcmp(ino,"0")==0)
break; //当学号等0时退出
scanf("%s",iname);//输入姓名
getchar();
scanf("%c%d",&isex,&iage);//输入性别和年龄
getchar();
p=(struct Node *)malloc(LEN);
strcpy(p->Member.No,ino);// 字符串复制函数
strcpy(p->Member.Name,iname);
p->Member.Sex=isex;
p->Member.Age=iage;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
if(head!=NULL)
q->next=NULL;
return head;
}
struct Node *del(struct Node *head,char no[6])
{
struct Node *p,*q;
p=head;
q=p;
while(p)
{
if(strcmp(p->Member.No,no)==0) //当学号等0时
{
if(p==head)
head=p->next;
else
{
if(p->next!=NULL)
q->next=p->next;
else
q->next=NULL;
}
printf("\n\t\t%s\t%s\t%c\t%d\n",p->Member.No,
p->Member.Name,
p->Member.Sex,p->Member.Age);
free(p); //释放p内存
break;
}
q=p;
p=p->next;
}
return head;
}
void prn(struct Node *head)
{
struct Node *p;
int i=1;
p=head;
printf("\n信息\t学号\t姓名\t性别\t年龄\n");
while(p)
{ printf("%3d\t%s\t%s\t%c\t%d\n",i,p->Member.No,
p->Member.Name, p->Member.Sex,p->Member.Age);
p=p->next;
i++; }// while(p)
}// void prn
void main()
{ struct Node *head;
char no[6];
head=create();
prn(head); //调用void prn(head)
getch();
printf("\n请输入要查找的学生学号:");
gets(no);
head=del(head,no);
prn(head);
getch();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -