|
|
1鱼币
#include<stdio.h>
#include<malloc.h>
#define NUM sizeof(struct student)
//----------------------------------------------------------------------------------
struct student *creat(); //创建一个链表
void print(struct student *head); //打印链表
struct student *del(struct student *head,int num); //删除结点
struct student *insert( struct student *head, struct student *stu2); //插入结点
//------------------------------------------------------------------------------------
struct student //结构体
{
int num;
float score;
struct student *next;
};
//------------------------------------------------------------------------------------
int n,i=1; //全局变量,计算结点
main()
{
struct student *stu,*p,stu2;
stu=creat();
p=stu;
print(p);
printf("please input delete num:"); //输入要删除的结点
scanf("%d",&n);
print(del(p,n));
//----------------------------------------------------------------
printf("please input insert num:"); //输入要插入的结点
scanf("%d",&stu2.num);
printf("please input insert score:"); scanf("%f",&stu2.score);
do
{
p=insert(stu,&stu2);
print(p);
i++;
}while(i<=80);
printf("\n\n");
system("pause");
}
//------------------------------------------------------------
struct student *creat()
{
struct student *head,*p1,*p2;
p1=p2=(struct student *)malloc(NUM); //
printf("input num:");
scanf("%d",&p1->num );
printf("input score:");
scanf("%f",&p1->score );
head=NULL;
n=0;
while(0!=p1->num)
{
n++;
if(1==n)
{
head=p1;
}
else
{
p2->next =p1;
}
p2=p1;
p1=(struct student *)malloc(NUM);
printf("\n");
printf("input num:");
scanf("%d",&p1->num );
printf("input score:");
scanf("%f",&p1->score );
}
p2->next =NULL;
return head;
}
//---------------------------------------------------------------
void print(struct student *head)
{
struct student *p;
printf("\nThere are %d records:\n",n);
p=head;
printf("\n\n");
if(0!=head)
{
do
{
printf("第%d号学生的%5.2f成绩:\n",p->num,p->score );
p=p->next;
printf("\n");
}while(0!=p);
}
}
//---------------------------------------------------------------
struct student *del(struct student *head,int num)
{
struct student *q1,*q2;
if(head==NULL)
{
printf("This is null.\n");
goto END;
}
q1=head;
while(num!=q1->num && q1->next!=NULL)
{
q2=q1;
q1=q1->next;
}
if(num==q1->num)
{
if(q1==head)
{
head=q1->next;
}
else
{
q2->next=q1->next;
}
printf("\ndelete No: %d succeed!\n",num);
n=n-1;
}
else
{
printf("\n %d Not been found!\n",num);
}
END:
return head;
}
//-----------------------------------------------------
struct student *insert( struct student *head, struct student *stu)
{
struct student *p1, *p2,*p0;
p0=stu;
p1 = head;
if( NULL == head )
{
head=p0;
p0->next=NULL;
}
printf("\n");
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;
}
n = n+1; // n是作为一个全局变量,用来记录链表的数据数。
printf("\n");
return head;
}
|
|