|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct student) //student结构的大小
struct student *creat(); //创建链表
struct student *del(struct student *head,int num); //del函数用于删除节点 *head为删除链表的头结点 num为删除节点的num
struct student *insert(struct student *head,struct student stu_2); //给链表中插入节点
void print(struct student *head); //打印链表
struct student
{
int num;
float score;
struct student *next;
};
int n; //全局变量,用来纪录存放了多少数据
void main()
{
struct student *stu,*p,stu_1;
int n;
stu=creat();
p=stu;
print(p);
/*
printf("please enter the num to delete:");
scanf("%d",&n);
print(del(p,n));
*/
printf("please insert new num:");
scanf("%d",&stu_1.num);
printf("please insert new score:");
scanf("%f",&stu_1.score);
print(insert(stu, stu_1));
printf("\n\n");
system("pause");
}
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
int n=0;
p1=p2=(struct student *)malloc(LEN); //LEN 是student 结构的大小
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&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);
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
}
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL)
return head;
else
{
p1=head;
while(p1->num!=num && p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->num==num)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
}
else
{
printf("lt's have been find it\n");
}
return head;
}
}
struct student *insert(struct student *head,struct student stu_2)
{
struct student *p1,*p0,*p2;
p1=head;
p0=&stu_2;
if(head!=NULL)
{
while((p0->num>p1->num ) && (p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(p1==head)
{
head=p0;
//p0->next=p1;
}
else
{
p2->next=p0;
//p0->next=p1;
}
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
else
{
head=p0;
p0->next=NULL;
}
return head;
}
void print(struct student *head)
{
struct student *p;
p=head;
if(head!=NULL)
{
do
{
printf("num %d\t score %f\t\n",p->num,p->score);
p=p->next;
}
while(p!=NULL);
}
else
printf("The list is null!");
}
|
|