c语言 :结构体与共用体

#include <stdio.h>
#include <malloc.h>
#define NULL 0              
#define LEN sizeof(struct info)      
/*定义结构体*/
struct info
{
int num;
float score;
struct info *next;
};
int n;        
/* 建立链表函数,返回值为一个指向链表头的指针*/
struct info *creat(void)     
{
struct info *head, *p1, *p2;
head=NULL;
n=0;                
p1=p2=(struct info *)malloc(LEN);
printf("Please input the number and score:\n");
scanf("%d%f", &p1->num, &p1->score);      
while(p1->num!=0)   
{
n=n+1;             
if(n==1)head=p1;       
else p2->next=p1;      
p2=p1;
p1=(struct info *)malloc(LEN);       
scanf("%d%f", &p1->num, &p1->score);
}
p2->next=NULL;   
free(p1);     
return(head);   
}
/*输出链表函数,返回值为指向链表头的指针*/
void print(struct info *head)  

struct info *p;
p=head;
if(head)        
do

printf("%d%5.1f\n", p->num, p->score);
p=p->next;
}while(p!=NULL);
}
/*删除链表内结点的函数,返回值为指向链表头的指针*/
struct info *del(struct info *head, int num) 
{
struct info *p1, *p2;
if(!head){printf("\nlist null!\n"); return(head);}    
p1=head;
while(num!=p1->num&&p1->next!=NULL)
{   p2=p1; p1=p1->next; }    
if(num==p1->num) 
{  if(p1==head)
head=p1->next;    
else
p2->next=p1->next;
free(p1);
printf("delete:%d\n",num);
}
else
printf("%d not been found!\n", num);
return(head);
}
/* 建立插入函数,返回值为指向链表头的指针*/
struct info *insert(struct info *head, struct info *stud)
{
struct info *p0, *p1, *p2;
p1=head;
p0=stud;
if(!head)
{head=p0;
p0->next=NULL;}
else
{ while((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(head==p1)head=p0;
else p2->next=p0;
p0->next=p1;
}
else{p1->next=p0;p0->next=NULL;}
}
return(head);
}
/*主函数*/
main()
{
struct info *head, *stu;
int delnum;
head=creat();                  
print(head);                                 /* 显示刚才建立的链表的全部内容 */
printf("\nPlease input the del num:");
scanf("%d",&delnum);
while(delnum)  /* 当输入的学号不为0时,要从链表中删除这个学号对应的结点 */
{
head=del(head, delnum);
print(head);
printf("\nPlease input the del num:");
scanf("%d", &delnum);
}
printf("\nPlease insert the record:");
stu=(struct info*)malloc(LEN);          /* 生成一新结点 */
scanf("%d%f", &stu->num, &stu->score);
while(stu->num!=0) /* 输入的学生号不为0时,插入到已有的链表中 */
{
head=insert(head, stu);      /* 调用前面的函数在链表中插入新结点 */
printf("\nPlease insert the record:");
stu=(struct info*)malloc(LEN);
scanf("%d%f", &stu->num, &stu->score);
}
free(stu);  /* 释放最后一个申请的结点,因为本结点的学生号为0,不被插入链表中 */
print(head);
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无敌小干货

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值