链表问题,请大家帮忙解答,我想知道我的为什么错误?
换了家新单位,不能上网,刚去没有什么事情,就想写个链表吧。假如将头指针作为参数应该很简单。(呵呵,有机会再试试)。假如像我现在这样使用全局指针,得不到正确的结果啊。
p->id=4,
p->next is not null
p->id=4,
p->next is null
this is a test for test4
以上是结果,明显是不对。为什么呢原因在哪里,请指教谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
int id;
// char name[20];
struct node *next;
};
struct node *init_node(struct node ptr);
struct node *head;
void add_node(struct node ptr);
void show_allnode(void);
int main(void)
{
struct node ptr;
ptr.id = 1;
ptr.next = NULL;
head = init_node(ptr);
ptr.id = 2;
ptr.next = NULL;
add_node(ptr);
ptr.id = 3;
ptr.next = NULL;
add_node(ptr);
ptr.id = 4;
ptr.next = NULL;
add_node(ptr);
show_allnode();
printf(" this is a test for test4\n");
return 0;
}
void show_allnode(void)
{
struct node *p;
p = head;
if (p == NULL)
{
printf("head is null\n");
}
printf(" this is a test for show all node\n");
while(p != NULL)
{
printf("p->id=%d,\n", p->id);
if (p->next == NULL)
{
printf("p->next is null\n");
}
else
{
printf("p->next is not null\n");
}
p = p->next;
}
}
struct node *init_node(struct node ptr)
{
struct node *head1 = (struct node *)malloc(sizeof(struct node) * 1);
if (headi1 == NULL)
{
printf("malloc error\n");
}
head1 = &ptr;
head = head1;
return head;
}
void add_node(struct node ptr)
{
struct node *p;
p = head;
if (p == NULL)
{
printf("head is null\n");
}
while(p->next != NULL)
{
p = p->next;
}
struct node *head1 = (struct node *)malloc(sizeof(struct node) * 1);
if (head1 == NULL)
{
printf("malloc error\n");
}
head1->id = ptr.id;
p->next = head1;
head1->next = NULL;
}