【发布时间】:2013-11-01 20:40:20
【问题描述】:
我对 C 语言编码非常陌生(因此我正在从事这项愚蠢的练习)。我尝试查看这个other solution 到类似的问题,但似乎我的编码策略不同,最终我想了解我的代码有什么问题。非常感谢您的意见。
我有一个链表、一个在我的链表开头插入一个新节点的函数、一个打印我的链表的函数和一个主函数。
不幸的是,我对 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.
【问题讨论】:
标签: c pointers linked-list printf insertion