链表的实现
#include <stdio.h>
#include <stdlib.h>
typedef struct linklist
{
int data;
struct linklist *next;
}linkli;
//linkli *head;
void init(linkli *head)
{
head=(struct linklist*)malloc(sizeof(struct linklist));
head->next=NULL;
return head;
}
void in(linkli *head,int x)
{
linkli *p,*q;
p=(struct linklist*)malloc(sizeof(struct linklist));
q=(struct linklist*)malloc(sizeof(struct linklist));
head=(struct linklist*)malloc(sizeof(struct linklist));
p=head;
q->data=x;
printf("line 26 x = %d\n",x);
printf("line 27 q -> data = %d\n",q->data);
q->next=p->next;
p->next=q;
}
void show(linkli *head)
{
linkli *p;
p=(struct linklist*)malloc(sizeof(struct linklist));
//head=(struct linklist*)malloc(sizeof(struct linklist));
p=head->next;
while(p!=NULL)
{
printf("line 37 \n");
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(int args,char argv[])
{
int x;
linkli *head;
init(head);
while(1)
{
scanf("%d",&x);
printf("line 50\n");
if(x==0)
break;
else
in(head,x);
printf("line 52\n");
}
show(head);
return 0;
}
为什么我的链表在打印的时候会出问题?
[解决办法]
要改为:
void init(linkli **head)
{
*head=(struct linklist*)malloc(sizeof(struct linklist));
*head->next=NULL;
}