链表与结点
实验内容:试编写一个程序完成:建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。
实验要求:(1)用链表实现。(2)输入事先已编好的程序,并运行该程序。分析运行结果是否正确。
(注意):利用malloc函数开辟存储空间的形式为:malloc(字节长度),返回值为第一个字节的指针。
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{char num[6];char name[8];char sex[2];int age;struct student *next;
}stu[10];
int main()
{struct student *p,*pt,*head;int i,length,iage,flag=1;int find=0;//找到待删元素find=1,否则find=0 while(flag==1){printf("input length of list(<10):");//输入链表长度,要求小于10 scanf("%d",&length);if(length<10)flag=0;}//建立链表for(i=0;i<length;i++){p=(struct student *)malloc(LEN);if(i==0)head=pt=p;elsept->next=p;pt=p;printf("NO.:");scanf("%s",p->num);printf("name:");scanf("%s",p->name);printf("sex:");scanf("%s",p->sex);printf("age:");scanf("%d",&p->age);} p->next=NULL;p=head;printf("\n NO. name sex age\n");//显示,输出已有结点的数据 while(p!=NULL){printf("%4s%8s%6s%6d\n",p->num,p->name,p->sex,p->age);p=p->next;} //删除结点printf("input age:");//输入待删年龄 scanf("%d",&iage);pt=head;p=pt;if(pt->age==iage)//链头是待删元素 {p=pt->next;head=pt=p;find=1;} else //链头不是待删元素pt=pt->next;while(pt!=NULL){if(pt->age==iage){p->next=pt->next;find=1;}else //中间结点不是待删元素 p=pt;pt=pt->next;} if(!find)printf("not found %d.",iage);p=head;printf("\n NO. name sex age\n");//显示结果 while(p!=NULL){printf("%4s%8s",p->num,p->name);printf("%6s%6d\n",p->sex,p->age);p=p->next;}return 0;
}