|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct Student) //定义LEN的数据类型
struct Student
{
int num;
float score;
struct Student *next;
};
int n; //定义全局变量,计算链表的个数
struct Student *creat() //建立一个建立动态链表的函数
{
struct Student *head; //定义头指针
struct Student *p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN); //开辟一个新单元
scanf("%d",&p1->num);
scanf("%f",&p1->score);
head=NULL; //把头文件清零
while(p1->num!=0) //只要数字不是0,就继续制作链表
{
n++;
if(n==1)
{
head=p1; //把头指针定义到链表第一个元素
}
else
{
p2->next=p1;//把p2的next指针指向p1的第一个成员
}
p2=p1;
p1=(struct Student*)malloc(LEN); //建立动态链表
scanf("%d",&p1->num);
scanf("%f",&p1->score);
} //只要学号不是0,就能一直制作,一旦到0,就跳出循环
p2->next=NULL; //只要p1指向0,那么p2就一直指向p1之前的
return(head); //返回头指针
}
void print(struct Student *head) //输出链表的函数
{
struct Student *p;
printf("\nNow,These %d record are:\n",n);
p=head;
if(head!=NULL) //只要头文件不是0,就一直打印
{
do
{
printf("%ld,%5.1f\n",p->num,p->score);
p=p->next;//让p指向下一个节点
}
while(p!=NULL);//只要p不是指向0就继续打印下一个成员
}
}
struct Student *shan(struct Student *head,int a)
{
struct Student *p1,*p2;
if(head==NULL)
{
printf("\nTHIS LIST IS NULL");
goto END;
}
p1=head;
while((*p1).num!=a&&(*p1).num!=NULL)
{
p2=p1;//p2向后移动一个位置
p1=p1->next; //P1向后移一个位置
}
if(p1->num==a) //p1是要删除的结点
{
if(p1==head) //如果p1是头结点
{
head=p1->next;//删除头结点
}
else
{
p2->next=p1->next; //删除当前结点
}
}
else
{
printf("can't find the number");
}
END:
return head;
}
int main()
{
struct Student *stu,*p;
int c;
stu=creat(); //调用建表函数,返回值赋值给stu
p=stu;
print(p); //调用打印函数
printf("please scanf a number");
scanf("%d",&c);
print(shan(p,c));
printf("\n\n");
system("pause");
}
程序在第一次打印链表之后,输入C之后后续删除链表步骤无法进行,求指导 |
|