gpt4 book ai didi

c - 链表节点创建

转载 作者:行者123 更新时间:2023-11-30 21:16:09 26 4
gpt4 key购买 nike

#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;
}

最佳答案

void push (node_t *root, int value)

root 节点永远不会返回给调用者。您需要接受 root 节点的 node_t* 作为指针,因此 node_t** 能够在其原始位置,或返回新分配的当前节点。

node_t * push (node_t *root, int value)

然后;

node_t * push (node_t *root, int value) {
node_t* current = root;
/*...*/
return current;
}

给出更新代码;上面的内容仍然适用,但是 main 中的演示示例需要修改。 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;
}

注意;这是使用 -std=c11 语言级别兼容性进行编译的。

关于c - 链表节点创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37608772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com