建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去(本题是教材第11章11.11)。

#include "stdio.h"
#include "stdlib.h"
#define NULL 0
int n;
 struct student
{
    int num;
    int age;
    char name[20];
    char gender[20];
    struct student *next;
};
 struct student *load(void)
 {
    struct student *p1,*p2,*head;
    char s1[20],s2[20];
    p1=p2=(struct student *)malloc(sizeof(struct student));
    printf("input num age name gender:\n");
    scanf("%d %d",&p1->num,&p1->age);
    scanf("%s",s1);scanf("%s",s2);strcpy(p1->name,s1);strcpy(p1->gender,s2);
    head=NULL;n=0;
    do
    {
        char s1[20],s2[20];
        n=n+1;
        if(n==1) head=p1;
        else p2->next=p1;
        p2=p1;
        p1=(struct student *)malloc(sizeof(struct student));
        printf("input num age name gender:\n");
        scanf("%d %d",&p1->num,&p1->age);
        scanf("%s",s1);scanf("%s",s2);strcpy(p1->name,s1);strcpy(p1->gender,s2);
    }while(p1->num!=0);
    p2->next=NULL;
    return(head);
 }
  void print(struct student *head)
 {
    struct student *p;
    p=head;
    do
    {
        printf("num:%d age:%d name:%s gender:%s\n",p->num,p->age,p->name,p->gender);
        p=p->next;
    }while(p!=NULL);
 }
  struct student *del(struct student *head,int age)
 {
    struct student *p1,*p2;
    if(head==NULL) {printf("\n list null!\n");goto end;}
    p1=p2=(struct student *)malloc(sizeof(struct student));
    p1=head;
    while(age!=p1->age&&p1->next!=NULL){p2=p1;p1=p1->next;}
    if(age==p1->age)
    {
        if(p1==head) head=p1->next;
        else p2->next=p1->next;           
        printf("delete:%d\n",age);n=n-1; 
    }
    else printf("age%d not been found!\n",age);
    end:return (head);
 }

 void main()
 {
    int num,cmd=1;
    struct student *head;
    head=load();
    system("cls");
    printf("these tables are following:\n ");
    print(head);
    while(cmd!=0){                /*我在这里设了一个CMD来防止发生因为多个学生的年龄是一个数字,当想多次删除的时候可以进行多次删除*/
    printf("you can delate one table,just input the age:\n");
    scanf("%d",&n);
    head=del(head,n);
    print(head);
    printf("if you dont want to delate any table,just put 0:");
    scanf("%d",&cmd);
    }
 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容