|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
/*
题目:创建几位同学的,学号以及成绩的单向动态链表。
我们约定学号不会为零,如果输入的学号为0,则表示建立链表的过程完成,
该结点不应连接到链表中。
如果输入的p1->num不等于0,则输入的是第一个结点数据(n=1),令head=p1,
即把p1的值赋给head,也就是使head也指向新开辟的结点p1所指向的新开辟的结
点就成为链表中第一个结点。
再开辟另一个结点并使p1指向它,接着输入该结点的数据。
如果输入的p1->num≠0,则应链入第2个结点(n=2), 将新结点的地址赋给第一
个结点的next成员。
接着使p2=p1,也就是使p2指向刚才建立的结点。
再开辟一个结点并使p1指向它,并输入该结点的数据。
在第三次循环中,由于n=3(n≠1),又将p1的值赋给p2->next,
也就是将第3个结点连接到第2个结点之后,并使p2=p1,使p2指向最后
一个结点。
再开辟一个新结点,并使p1指向它,输入该结点的数据。由于p1->num的值为0,
不再执行循环,此新结点不应被连接到链表中。
将NULL赋给p2->next。
建立链表过程至此结束,p1最后所指的结点未链入链表中,第三个结点的next成
员的值为NULL,它不指向任何结点。
首先要知道链表第一个结点的地址,也就是要知道head的值。
然后设一个指针变量p,先指向第一个结点,输出p所指的结点,然后使p后移
一个结点,再输出,直到链表的尾结点。
*/
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define LEN sizeof(struct student) //声明.宏定义.创建 student结构的大小空间。
struct student * creat(); //声明.创建一个返回值为结构体指针变量的自定义函数.链表。
void print(struct student *head); //声明.一个参数为结构体指针变量的自定义函数.打印链表。
int n; //声明.全局变量,用来记录存放了多少数据。
struct student * del(struct student *head,int num); //del函数用于删除结点.
struct student * insert(struct student *head, struct student *stu2); // 插入的结点.
struct student //声明定义.一个结构体。
{
int num;
float score;
struct student *next; //声明.一个结构体指针变量,是为了指向下一个同结构体的节点。
}; //*stu, *head,*p1,*p2;
void main()
{
struct student *stu,stu2; //声明.一个局部的结构体指针变量。
int n;
stu = creat();
print( stu );
printf("\n请输入要删除的学号:");
scanf("%d",&n);
print(del(stu,n));
printf("\n请输入要添加同学的学号:"); scanf("%d",&stu2.num);
printf("请输入要添加同学的成绩:"); scanf("%f",&stu2.score);
print(insert(stu, &stu2));
printf("\n"); system("pause");
}
struct student * creat() //定义.创建一个返回值为结构体指针变量的自定义函数.链表
{
struct student *head;
struct student *p1,*p2;
p1=(struct student *) malloc(LEN);//为结构体指针变量申请一个宏定义名为LEN的空间大小。
printf("请输入此同学的学号:"); scanf("%d",&(*p1).num);
printf("请输入此同学的成绩:"); scanf("%f",&p1->score);
head=NULL; n=0; p2=p1;
while(p1->num!=0)
{
n++;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2 = p1;
p1 = (struct student *) malloc(LEN);
printf("请输入此同学的学号:"); scanf("%d",&(*p1).num);
printf("请输入此同学的成绩:"); scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
}
void print(struct student *head)
{
struct student *p;
p=head;
printf("\n有%d位同学:\n",n);
if(head!=NULL)
{
do
{
printf("学号为%d的成绩是:%f\n",p->num,p->score);
p=p->next;
}while (p!=NULL);
}
}
struct student * del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL)
{
printf("此链表是空的!");
goto end;
}
p1=head;
while (num!=p1->num && p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)
{
if(head==p1)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
printf("已经成功删除了该学号:%d",num);
n=n-1;
}
else
{
printf("此学号不存在!");
}
end:
return head;
}
struct student *insert(struct student * head, struct student *stu2)
{
struct student *p1,*p2,*p0;
p1=head; p0=stu2;
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(p1==head)
{
head=p0;
}
else
{
p2->next=p0;
}
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
n=n+1;
return head;
}
|
|