新人学习链表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int num;
char name[30];
struct student *next;
};
void create(struct student*p);
void display(struct student*p);
int main()
{
struct student *head;
head=(struct student*)malloc(sizeof(struct student));
head->next=NULL;
create(&head);
display(&head);
system("pause");
return 0;
}
void create(struct student*p)
{
struct student*q;
int num;
char name[30];
q=p;
while(1)
{
printf("请输入学号:");
scanf("%d",&num);
if(num==0)
{
p->next=NULL;
break;
}
printf("请输入姓名");
scanf("%s",name);
strcpy(p->name,name);
p->num=num;
q=(struct student*)malloc(sizeof(struct student));
p->next=q;
p=q;
}
}
void display(struct student*p)
{
while(p!=NULL)
{
printf("%d %s ",p->num,p->name);
p=p->next;
}
}
这个链表编译输出都通过了,就是会在最后输出一行垃圾值,不知道链表结尾怎么错了
[解决办法]
这明显不行,
create(&head);display(&head);改为create(head);display(head);并不是把指针的地址给函数
[解决办法]
strcpy(p->name,name); p->num=num; q=(struct student*)malloc(sizeof(struct student)); p->next=q; p=q;
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
int num;
char name[30];
struct student *next;
};
struct student* create(struct student*p);
struct student* display(struct student*p);
int main()
{
struct student *head;
head=(struct student*)malloc(sizeof(struct student));
head->next=NULL;
head=create(head);
head=display(head);
system("pause");
return 0;
}
struct student* create(struct student*p)
{
struct student *head=p;
struct student*q;
int num;
char name[30];
q=p;
while(1)
{
printf("请输入学号:");
scanf("%d",&num);
if(num==0)
{
p->next=NULL;
break;
}
printf("请输入姓名");
scanf("%s",name);
strcpy(p->name,name);
p->num=num;
q=(struct student*)malloc(sizeof(struct student));
p->next=q;
q->next=NULL;
p=q;
}
return head;
}
struct student* display(struct student*p)
{
struct student *head=p;
while(p->next!=NULL)
{
printf("%d %s ",p->num,p->name);
p=p->next;
}
return head;
}
[解决办法]
开始学习链表最好是在纸上画一画,各个指针的指向,多画几次就懂了