C语言程序设计第四版(谭浩强)9.12 建立一个链表,每个结点包括:学号,姓名,性别,年龄。输入一个年龄,如果链表中的结点包含此年龄,则将此结点删去。

//*作者:冰糖
//*日期:2018年12月1日
//*章节:第九章
//*题号:12 
//*题目:建立一个链表,每个结点包括:学号,姓名,性别,年龄。输入一个年龄,如果链表中的结点包含此年龄,则将此结点删去。 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N sizeof(struct student)
struct student
{
	int num;
	char name[20];
	char sex[1]; 
	int age;
	struct student *next;
};
int num;
int n;
int main()
{
	struct student *creat();
	struct student *dele(struct student *head);
	void print(struct student *h);
	struct student *hhh,*si;
	hhh=creat();
	printf("\n链表的信息为:\n");
	print(hhh); 
	printf("\n请输入要删除的年龄:\n"); 
	scanf("%d",&num);
	si=dele(hhh);
	printf("\n删除后链表的信息为:\n");
	print(si);
	return 0;
}
struct student *creat()
{                                              
    struct student *head,*p1,*p2;
    head=NULL;
    p1=p2=(struct student *)malloc(N);
    printf("请输入第1个结点的学号,姓名,性别,年龄:\n");
    scanf("%d %s %s %d",&p1->num,&p1->name,&p1->sex,&p1->age);
    while(p1->num!=0){
            n++;
            printf("请输入第%d个结点的学号,姓名,性别,年龄:(学号为零时终止)\n",n+1);
            if(n==1) head=p1;
            else p2->next=p1;
            p2=p1;
            p1=(struct student *)malloc(N);
            scanf("%d %s %s %d",&p1->num,&p1->name,&p1->sex,&p1->age);

    }
    p2->next=NULL;
    return head;
}

struct student *dele(struct student *head)
{           
	struct student *p1,*p2;  
	if(head==NULL)
	{  
		printf("空表.\n");
		return NULL;
	}
	p1=head;
    while(p1->age!= num && p1->next!=NULL)
    { 	p2=p1;       
	p1=p1->next;
    }
    if(p1->age==num)                     
   {  	if(p1==head)
	     head=p1->next;
		else 
	     p2->next = p1->next; 
	printf("含有年龄%d的链表已被删除。\n", p1->age);
	free(p1);
    }
    else 
    	printf("含有年龄%d的链表未找到。\n", num);
    return(head);
}
void print(struct student *h)
{ 	struct student *p = h; 
	if(p == NULL) 
		printf("空表\n");
 	while(p != NULL) 	
	{ 		
		printf("%d %s %s %d\n",p->num,p->name,p->sex,p->age);
 		p = p->next; 
	} 	
	printf("\n");
}                       
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值