C语言_动态链表的简单建立与节点删除

来源:互联网 发布:php手册 编辑:程序博客网 时间:2024/04/30 19:52

程序详解:

       1、输入学生的姓名和年龄,进行顺序排列。

       2、删除其中某位学生的数据

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TITLE 45
typedef struct{
    int age;
    char name[TITLE];
    struct student *next;
    }stu;
    void del(char *d_name);
    stu *head=NULL,*p1,*p2;


main()
{
    int i=0;
char c_name[TITLE],cc_name[TITLE];


printf("请输入第一位学生的姓名(按回车键结束输出):\n");
while(gets(c_name)!=NULL&&c_name[0]!='\0')
{
   p1=(stu *)malloc(sizeof(stu));
   if(head==NULL)
      head=p1;
   else
    p2->next=p1;
   p1->next=NULL;
   strcpy(p1->name,c_name);
   printf("请输入该学生的年龄:\n");
   scanf("%d",&p1->age);
        while(getchar()!='\n')
     continue;
   p2=p1;
   printf("请输入下一位学生的姓名(按回车键结束输出):\n");
   }
   p1=head;
   while(p1!=NULL)
   {
       printf("第%d位学生的姓名是%s,年龄是%d\n",++i,p1->name,p1->age);
       p1=p1->next;
        }
        del(cc_name);
}
void del(char *d_name)
{   int i=0;
    p1=head;
    printf("输入要删除的学生的姓名;\n");
    scanf("%s",d_name);
    if(strcmp(d_name,head->name))
    {
        while(strcmp(d_name,p1->name))
    {
        p2=p1;
        p1=p1->next;
    }
    p2->next=p1->next;
    }
    else
    head=p1->next;


    p1=head;
   while(p1!=NULL)
   {
       printf("第%d位学生的姓名是%s,年龄是%d\n",++i,p1->name,p1->age);
       p1=p1->next;
        }
        p1=head;
        while(p1!=NULL)
        {
            free(p1);
            p1=p1->next;
        }
        printf("完毕!\n");


}

0 0
原创粉丝点击