#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);
}
c语言 :结构体与共用体
最新推荐文章于 2024-08-16 08:54:14 发布