资源描述
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
int num;
float score;
struct student *next;
};
void main() //主函数
{
struct student *creat(void);//建立一个动态链表
struct student *del(struct student *head,int del_num);//删除链表
struct student *insert(struct student *head,struct student *stu);//插入链表
void print(struct student *head);//输出链表
struct student *head;
struct student *stu; //要插入的节点
int del_num;
head=creat(); //创建动态链表
print(head); //输出原链表
printf("\n"); //空一格
printf("Input the delete del_num:");
scanf("%d",&del_num);
while(del_num!=0) //多次删除
{
head=del(head,del_num);
printf("\n");
printf("The deleted list is:\n");
print(head);
printf("\n");
printf("Input the delete del_num:");
scanf("%d",&del_num);
}
printf("\n");
printf("Input the insert node:");
stu=(struct student*)malloc(LEN);
scanf("%d,%f",&stu->num,&stu->score);
while(stu->num!=0) //多次插入
{
head=insert(head,stu);
print(head);
printf("\n");
printf("Input the insert node:");
stu=(struct student*)malloc(LEN);
scanf("%d,%f",&stu->num,&stu->score);
}
}
/***************************************************/
/***************建立动态链表************************/
struct student *creat(void) //建立一个动态链表
{ int n;
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student*)malloc(LEN);
scanf("%d,%f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct student*)malloc(LEN);
scanf("%d,%f",&p1->num,&p1->score);
}
p2->next=NULL;
return(head);
}
/***************************************************/
/***************删除链表***************************/
struct student *del(struct student *head,int del_num)
{
struct student *p1,*p2;
if(head==NULL)
printf("This is a null list!\n");
p1=head;
while(del_num!=p1->num&&p1->num!=NULL)
{
p2=p1;
p1=p1->next;
}
if(del_num==p1->num)
{
if(p1==head) head=p1->next;
else p2->next=p1->next;
printf("delete:%d\n",del_num);
}
else printf("%d not been found!\n",del_num);
return(head);
}
/***************************************************/
/***************插入链表节点************************/
struct student *insert(struct student *head,struct student *stu)
{
struct student *p0,*p1,*p2;
p1=head;
p0=stu;
if(head==NULL)
{ 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);
}
/***************************************************/
/***************输出链表****************************/
void print(struct student *head)
{
struct student *p;
p=head;
do
{
printf("%d%5.0f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
注意:运行时,每输入些组数据后,回车输入“0”,然后回车。
展开阅读全文