链接列表节点创建

时间:2016-06-03 07:45:44

标签: c linked-list

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

1 个答案:

答案 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; } 语言级别兼容性编译的。