#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node* next;
} node_t;
void push (node_t *root, int value) {
node_t* current = root;
if(current == NULL) {
current = (node_t*)malloc(sizeof(node_t));
current->value = value;
current->next = NULL;
}
else {
while(current->next != NULL)
current = current->next;
current = (node_t*)malloc(sizeof(node_t));
current->value = value;
current->next = NULL;
}
}
void print (node_t* root) {
node_t* current = root;
while(current != NULL) {
printf("%d ", current->value);
current = current->next;
}
}
//////////////////////////////////////////////////////////////////
int main(void) {
node_t* root = NULL;
push(root, 5);
push(root, 10);
push(root, 15);
print(root);
return 0;
}
为什么此代码不起作用?
我试图在main
中创建一个没有初始化的链表。有可能吗?
我希望它从root
获取未初始化的main
节点并在函数push()
中初始化它,因此它是链表中的第一个节点。
我不想这样做:
int main() {
node_t* root = (node_t*)malloc(sizeof(node_t));
root->value = 0;
root->next = NULL;
}
答案 0 :(得分:4)
void push (node_t *root, int value)
root
节点永远不会返回给调用者。您需要接受node_t*
节点的root
作为指针,因此node_t**
能够在其原始位置分配根,或者返回新分配的{{1} } node。
current
然后;
node_t * push (node_t *root, int value)
给出更新代码;以上仍然适用,但您在main中演示样本需要修改。 node_t * push (node_t *root, int value) {
node_t* current = root;
/*...*/
return current;
}
选项会更好。
您的node_t**
功能有两个问题;接受push()
并在创建node_t**
节点时设置它;并在已创建root
时正确插入新节点;
root
完整列表;
// accept the root as node_t**
void push (node_t **root, int value) {
node_t* current = *root; // get the root node
if (current == NULL) {
current = (node_t*)malloc(sizeof(node_t));
current->value = value;
current->next = NULL;
*root = current; // set the root node
}
else {
while (current->next != NULL) {
current = current->next;
}
// create the new node in the place of the "next" node
current->next = (node_t*)malloc(sizeof(node_t));
current->next->value = value;
current->next->next = NULL;
}
}
注意的;这是使用#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node* next;
} node_t;
void push (node_t **root, int value) {
node_t* current = *root;
if (current == NULL) {
current = (node_t*)malloc(sizeof(node_t));
current->value = value;
current->next = NULL;
*root = current;
}
else {
while (current->next != NULL) {
current = current->next;
}
current->next = (node_t*)malloc(sizeof(node_t));
current->next->value = value;
current->next->next = NULL;
}
}
void print (node_t* root) {
node_t* current = root;
while(current != NULL) {
printf("%d ", current->value);
current = current->next;
}
}
int main(void) {
node_t* root = NULL;
push(&root, 5); // note the additional &
push(&root, 10);
push(&root, 15);
print(root);
return 0;
}
语言级别兼容性编译的。