【问题标题】:Inserting to beginning of linked list (revisited)插入到链表的开头(重新访问)
【发布时间】: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


    【解决方案1】:

    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


    为什么你只得到 15 最后一个节点 (temp3) 的值?

    因为在 main 中您创建了三个临时节点并将每个节点的下一个节点初始化为 NULL,包括 list 节点,因此在 add_to_list() 函数中,如果条件 ((*list)-&gt;next == NULL) 始终评估为 true 并且 list 始终使用临时节点初始化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多