我正在尝试理解链接列表。我创建了这个代码,它应该给我链接列表的经验。当我运行此代码时,我得到0,但输出应为10,9,8,7,6,5,4,3,2,1,0。有人可以帮我解决这个问题吗?
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int value;
struct node *next;
}node;
node * addnode (node *ptr, int value);
void traverse(node *ptr);
int main (void)
{
int i;
node *ptr,*root;
root=(node *)malloc(sizeof(node));
ptr=root;
root->value=0;
root->next=0;
for(i=1;i>10;i++)
ptr=addnode(ptr,i);
traverse(ptr);
return(0);
}
void traverse(node *ptr)
{
printf("%d\n",ptr->value);
if(ptr->next) /*assuming that the pointer to the next node is initialized to NULL, so if its NULL then the if codeblock won't execute*/
traverse(ptr->next);
}
node * addnode (node *ptr, int value)
{
node *newnode;
newnode=(node *)malloc(sizeof(node));
newnode->value=value;
newnode->next=ptr;
return(newnode);
}
答案 0 :(得分:0)
您的代码存在两个问题:
traverse(root)
代替traverse(ptr)
。你可以这样做(source):
void Push(struct node** headRef, int newData) {
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->data = newData;
new_node->next = *headRef;
*headRef = new_node;
}
在你的情况下看起来像:
void addnode(struct node** headRef, int newData) {
struct node* new_node =
(struct node*) malloc(sizeof(struct node));
new_node->value = newData;
new_node->next = *headRef;
*headRef = new_node;
}
然后添加如下节点:addnode(&root, some_value);