c - 指向链表开头的指针

标签 c struct linked-list append singly-linked-list

我在学习指针时练习链表结构,但在列表中 append 项目时遇到问题。这是我的代码

#include <stdio.h>
#include <stdlib.h>

typedef struct node node_t;
struct node {
    int data;
    node_t* next;
};

void append(node_t *head, int data) {
    if (head == NULL) {
        node_t *node = (node_t*)malloc(sizeof(node_t*));
        node->data = data;
        node->next = NULL;
        head = node;
    } else {
        node_t *node = (node_t*)malloc(sizeof(node_t*));
        node->data = data;
        node->next = NULL;

        if (head->next == NULL) {
            head->next = node;
        } else {
            node_t *current = head;
            while (1) {
                if (current->next == NULL) {
                    current->next = node;
                    break;
                }
                current = current->next;
            }
        }
    }
}

int main(void) {
    node_t *head = NULL;

    append(head, 4);
    append(head, 6);
    printList(head);

    return 0;
}

当我执行 head = node; 时,我的代码会中断,它不会更改 mainhead 的值。我想我错过了一些东西,但不确定是什么。 预先感谢您

最佳答案

您在函数append 中按值传递指针头。因此该函数处理传递给它的指针的副本。更改副本不会影响原始指针。通过引用传递它或从函数返回更新的头。

第一种方法要好得多。

该函数可以如下所示

int append( node_t **head, int data )
{
    node_t *node = malloc( sizeof( node_t ) );
    int success = node != NULL;

    if ( success )
    {
        node->data = data;
        node->next = NULL;

        while ( *head != NULL ) head = &( *head )->next;

        *head = node;
    }

    return success;
}

这是一个演示程序。

#include <stdio.h>
#include <stdlib.h>

typedef struct node node_t;
struct node
{
    int data;
    node_t *next;
};

int append( node_t **head, int data )
{
    node_t *node = malloc( sizeof( node_t ) );
    int success = node != NULL;

    if ( success )
    {
        node->data = data;
        node->next = NULL;

        while ( *head != NULL ) head = &( *head )->next;

        *head = node;
    }

    return success;
}

void printList( node_t *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }

    puts( "null" );
}

int main(void) 
{
    node_t *head = NULL;

    const int N = 10;

    for ( int i = 0; i < N; i++ )
    {
        append( &head, i );
    }

    printList( head );

    return 0;
}

它的输出是

0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> null

关于c - 指向链表开头的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60136635/

相关文章:

c - 逻辑错误行文件在哪里

c - 无法理解 C 编程中的逻辑表达式

c++ - 如何读/写二进制文件中的结构?

c - 链接列表打印问题?

c - 迭代列表 lst 并将函数 f 应用于每个链接以创建 “fresh” 列表

c - 我如何理解以下程序中的 while、do...while 和increment 运算符?

c - strrev() 函数在 Linux 中不可用吗?

pointers - 反射匿名结构体字段指针

使用链表的 malloc() 和 free 的正确方法

异或链表的C代码