关于C语言的链表~非常感谢
发布网友
发布时间:2024-10-11 19:34
我来回答
共2个回答
热心网友
时间:2024-12-01 15:00
//WIN-TC是什么turbo? 我在DEV-C下改的,应该也没问题吧
#include<stdio.h>
#include<malloc.h>
//#define NULL 0 //不用重定义NULL把,空指针用NULL就可以
struct student
{
int num;
char name[20];
float score;
struct student *next;
};
int n=0;
/*建立动态链表*/
/* 这个函数,有重要的问题,你在函数里创建了临时类,st,head指向它,但是当这个函数结束时,这个类会被销毁,head将是个没有指向的指针,所以当在函数中返回类时,需要堆分配内存
*/
struct student *creat(void)
{
struct student *p1=NULL,*head=NULL; // 这里一个学生类指针即可
struct student *st = (struct student *)malloc(sizeof(struct student)); //同上解释
printf("Please input records:\n");
scanf("%d%s%f",&(st->num),st->name,&(st->score));
p1=st;
p1->next = NULL;
if(st->num!=0)
head=p1;
while(p1->num!=0)
/*这个链表的创立,无非就是那些步骤,你必然明白,再不行,画个示意图就明白了,注意的是,什么时候指针赋值,什么时候用指针控制变量
*/
{n=n+1;
printf("%dEnd\n",n);
p1->next = (struct student *)malloc(sizeof(struct student));
//这句话至少得有一个“->”,需要控制变量
p1->next->next = NULL;
scanf("%d%s%f",&(p1->next->num),p1->next->name,&(p1->next->score));
if(n!=1)
{
p1 = p1->next;
}
}
printf("\nOver.\n");
/*printf("%o\n",head);
if(head!=NULL)
printf("%10d%10s%10.1f\n",head->num,head->name,head->score);*/
return(head);
}
/*输出*/
void print(struct student *head)
{
struct student *p;
p=head;
/*printf("%o\n",head);*/
getch();
//if(head==NULL)
//printf("\nList null!\n");
//else
printf("\nNow,there are %d records:\n",n);
while(p!=NULL)
{
printf("%10d%10s%10.1f\n",p->num,p->name,p->score);
p=p->next;
}
}
int main()
{
struct student *head;
head=creat();
/*printf("%o\n",head);
if(head!=NULL)
printf("%10d%10s%10.1f\n",head->num,head->name,head->score);*/
print(head);
getch();
return 0;
}
/*还有些小问题,如应该创建个销毁链表函数,使堆中内存被释放,等
但不影响达到效果,做个示意够了
*/
热心网友
时间:2024-12-01 15:01
#include<stdio.h>
#include<malloc.h>
#define NULL 0
struct student
{
int num;
char name[20];
float score;
struct student *next;
};
int n=0;
/*建立动态链表*/
struct student *creat(void)
{
struct student *p1,*p2,*head=NULL;
//struct student st;
p1=(struct student *)malloc(sizeof(struct student));
printf("Please input records:\n");
scanf("%d%s%f",&p1->num,p1->name,&p1->score);//应该就这里错了,可能是形式不能匹配
//scanf("%d%s%f",&st.num,st.name,&st.score);
p2=p1;//=&st;
if(p1->num!=0)
head=p1;
while(p1->num!=0)
{n=n+1;
printf("%dEnd\n",n);
if(n!=1)
{
p2->next=p1;
p2=p1;
}
p1=(struct student *)malloc(sizeof(struct student));
scanf("%d%s%f",&p1->num,p1->name,&p1->score);
}
p2->next=NULL;
printf("\nOver.\n");
/*printf("%o\n",head);
if(head!=NULL)
printf("%10d%10s%10.1f\n",head->num,head->name,head->score);*/
return(head);
}
/*输出*/
void print(struct student *head)
{
struct student *p;
p=head;
printf("***%s\n",head->name);
//getchar();
if(head==NULL)
printf("\nList null!\n");
else
printf("\nNow,there are %d records:\n",n);
while(p!=NULL)
{
printf("%10d%10s%10.1f\n",p->num,p->name,p->score);
p=p->next;
}
}
void main()
{
struct student *head;
head=creat();
/*printf("%o\n",head);
if(head!=NULL)
printf("%10d%10s%10.1f\n",head->num,head->name,head->score);*/
print(head);
//getchar();
}