#include<stdio.h>
#include<stdlib.h>
/*题目: 建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个
年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。 */
typedef struct Student //定义结构体
{
int num;
char name[20];
char sex;
int age;
struct Student *next;
}STU;
STU *creat(int n) //创建有n个结点的链表
{
STU *head,*p,*prep;
if((head = prep = (STU *)malloc(sizeof(STU))) != NULL)
for(int i=1;i<n;i++)
{
if((p = (STU *)malloc(sizeof(STU))) == NULL)
{
printf("Failure to apply for space "); //判断是否申请空间成功
exit(0);
}
prep->next=p;
prep=p;
}
else
{
printf("Failure to apply for space ");
exit (0);
}
p->next=NULL;
return head;
}
void assign(STU *head) //用文件给链表里的数据域赋值
{
STU *p = head;
FILE *fp;
if((fp = fopen("text","w+")) !=NULL)
{
fprintf(fp,"001,1号,M,18,002,2号,F,17,003,3号,M,18,004,4号,F,17");
fseek(fp,0l,SEEK_SET);
for(;p;)
{
fscanf(fp,"%d,%[^,],%c,%d,",&(p->num),p->name,&(p->sex),&(p->age));
p=p->next;
}
}
else
{
printf("The file text was not open");
exit(-1);
}
/*不能这样赋值
STU *p=head;
(*p)={001,"1号",'M',18};
p=p->next;
(*p)={002,"2号",'F',17};
p=p->next;
(*p)={003,"3号",'M',18};
p=p->next;
(*p)={004,"4号",'F',17};*/
}
STU* mydlt(STU *head,int age) //输入一个年纪,删减掉有 同龄的节点
{
STU *p,*prep;
for(p=prep=head;p;)
{
if(p==head && p->age==age)
{
prep=head=p->next;
free(p);
p=prep;
}
else if(p->age==age)
{
prep->next = p->next;
free(p);
p=prep->next;
}
else
{
prep=p;
p=p->next;
}
}
return head;
}
void show(STU *p) //展示在命令框里
{
do{
printf("%d %s %c %d\n",p->num,p->name,p->sex,p->age);
}while(p=p->next);
puts("");
}
int main()
{
int age;
scanf("%d",&age);
STU *head;
head=creat(4);
assign(head);
show(head); //原数据
head=mydlt(head,age);
show(head);
}
文件与链表的结合
最新推荐文章于 2024-06-06 09:00:00 发布