建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。最近接触到了链表的编程学习,遇到这样的比较基础的编程,程序表现大致分为几个步骤:
1、建立一个链表,编写一个建立链表的函数,并输入学号、姓名、性别、年龄,这些信息,
2、编写一个删除输入要求年龄的函数。
3、编写一个链表输出函数。
#include <stdio.h>
#include <stdlib.h>
typedef struct stu{
int num;
char name[10];
char sex;
int age;
struct stu *next;
}STU,*STUP; //声明一个结构体,里面包含学号、姓名、性别、年龄,还该结构体指针。
#define LEN sizeof(STU)
int main()
{
STUP head;
STUP creat(void); //建立链表函数。
STUP delet(STUP head,int age_temp);//删除要求年龄函数。
void print(STUP head);//输出链表函数
int age_temp;
printf("请输入学号、姓名、性别、年龄:\n");
head=creat();
print(head);
printf("请输入要删除的年龄:\n");
scanf("%d",&age_temp);
head=delet(head,age_temp);
printf("输出删除后的信息:\n");
print(head);
}
STUP creat(void) //建立链表函数
{
STUP p1,p2,head;
int n=0;
p1=p2=(STUP)malloc(LEN);
head=NULL;
scanf("%d %s %c %d",&p1->num,p1->name,&p1->sex,&p1->age);
while(p1->num!=0)
{
n=n+1;
if(n==1)
head=p1;
else p2->next=p1;
p2=p1;
p1=(STUP)malloc(LEN);
scanf("%d %s %c %d",&p1->num,p1->name,&p1->sex,&p1->age);
}
p2->next=NULL;
return head;
}
void print(STUP head) //输出链表函数
{
STUP p;
p=head;
if(head!=NULL)
do{
printf("%5d%7s%4c%5d\n",p->num,p->name,p->sex,p->age);
p=p->next;
}while(p!=NULL);
}
STUP delet(STUP head,int age_temp) //删除要求年龄函数
{
STUP h,p;
h=(STUP)malloc(LEN); //创建一个空结点
h->next=head;
head=h;
for(p=head;p->next!=NULL;p=p->next)
if(p->next->age==age_temp)
p->next=p->next->next;
head=head->next;
return head;
}