下次,请附上代码不要图片!
输入格式不对 scanf("%s,%ld", p1->name, &p1->num); 去掉逗号,
print()函数中, malloc()内存分配是随机的不是连续的, 所以p++到不了真正的下一个节点,
creat()函数中,上下节点没有正确连接,
释放节点要一个一个来,你原来写得只是释放了最后申请的那一个。
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define len sizeof(struct student)
struct student
{
char name[255];
long num;
student *next;
};
void delnode(struct student *head)
{
if (head == NULL)
return;
struct student *p = head;
struct student *t;
while (NULL != p)
{
t = p;
p = p->next;
free(t);
}
head = NULL;
return;
}
void main()
{
struct student *creat();
void print(student *head);
struct student *head;
head = creat();
print(head);
delnode(head);
system("pause");
}
student *creat()
{
student *head, *p1, *p2=NULL;
int n;
head = NULL;
printf("please input the name and number of the student:\n");
for (n = 1; n < 4;n++)
{
p1 = (student *)malloc(len);
scanf("%s%ld", p1->name, &p1->num);
if (n == 1)
{
head = p1;
p2 = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
p2->next = NULL;
}
return (head);
}
void print(student *head)
{
student *p;
p = head;
while (p)
{
printf("姓名: %s\t,学号: %ld\n", p->name, p->num);
p = p->next;
}
}