我对用 C 编写代码非常陌生(因此我正在做这个愚蠢的练习)。我试着看这个 other solution类似的问题,但似乎我的编码策略不同,最终我想了解我的代码有什么问题。非常感谢您的意见。
我有一个链表、一个在列表开头插入新节点的函数、一个打印链表的函数和 main 函数。
不幸的是,我对 C 的了解还不足以理解为什么我的函数没有插入到列表的开头。更不幸的是这段代码并没有崩溃。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} *Node_t;
void print_list(Node_t root) {
while (root) {
printf("%d ", root->data);
root = root->next;
}
printf("\n");
}
void add_to_list(Node_t *list, Node_t temp){
// check if list is empty
if ((*list)->next == NULL) {
// insert first element
(*list) = temp;
}
else {
temp->next = (*list);
(*list) = temp;
}
}
int main () {
int val1 = 4;
int val2 = 8;
int val3 = 15;
Node_t list = malloc(sizeof(struct Node));
Node_t temp1 = malloc(sizeof(struct Node));
Node_t temp2 = malloc(sizeof(struct Node));
Node_t temp3 = malloc(sizeof(struct Node));
temp1->data = val1;
temp1->next = NULL;
temp2->data = val2;
temp2->next = NULL;
temp3->data = val3;
temp3->next = NULL;
//Initialize list with some values
list->data = 0;
list->next = NULL;
/* add values to list */
add_to_list(&list,temp1);
add_to_list(&list,temp2);
add_to_list(&list,temp3);
print_list(list);
}
这段代码只会打印我试图添加到列表中的最后一个节点,因此会覆盖之前的节点。
例如:
Running…
15
Debugger stopped.
Program exited with status value:0.
最佳答案
add_to_list()
函数中的一个错误:
if ((*list)->next == NULL) { // checks next of first is NULL not list is NULL
// to insert at first
应该只是:
if ((*list) == NULL){ // You need to check list is NULL
检查 working code
Why you were getting only
15
the last node (temp3
) value?
因为在 main 中您创建了三个临时节点并将每个节点的 next 初始化为 NULL,包括 list
节点所以在 add_to_list()
函数中 if condition (( *list)->next == NULL)
始终评估为 true 并且 list
始终使用临时节点进行初始化。
关于c - 插入到链表的开头(重新访问),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543924/