下面是建立一个链表和打印链表的函数
输入0为结束
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* creat_list()
{
struct ListNode *head=(struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *tmp=head;
head->next=NULL;
while(1)
{
int num;
scanf("%d",&num);
struct ListNode *p=(struct ListNode *)malloc(sizeof(struct ListNode));
p->val=num;
// p->next=NULL;//把这句注释掉
if(num==0)
{
free(p);5
return head->next;
}
tmp->next=p;
tmp=tmp->next;
}
}
int print_list(struct ListNode *head)
{
printf("the val of list is\n");
while(head)
{
printf("%d\n", head->val);
head=head->next;
}
printf("the list output done\n");
return 0;
}
int main(void)
{
struct ListNode *head, *head_new;
head=creat_list();
print_list(head);
return 0;
}
运行结果如下
原因是链表的尾指针没有是NULL,变成了野指针,指向垃圾内存。