繁体   English   中英

指针C链表添加总是NULL

[英]Pointers C Linkedlist Adding Always NULL

我已经编写了一个函数,用于在C中添加到单链表的末尾。但是,我没有得到的是为什么head元素为NULL,为什么在连续添加后它仍保持为NULL。

该结构定义如下:

typedef struct node* node;

struct node {
    int data;
    node next;
}

总的来说,我有这个:

node test = NULL;
add(test,1);
add(test,2);
add(test,3);

函数add的定义如下:

void add(node head, int newData) {
    node n = createNode(newData);
    if (head==NULL) {
        head = n;
        return;
    }
    else {
        node tmp = head;
        while (tmp->next != NULL) {
           tmp = tmp->next;
        }
        tmp = n;
    }
}

createNode的定义如下:

node createNode(int data) {
    node n = (node) malloc(sizeof(struct node));
    n->next = NULL;
    n->data = data;
    return n;
}

我感到困惑的是,如果我首先初始化head(节点test = createNode(1)),然后继续添加其余值,那么add函数就可以正常工作。 但是,如果我将测试节点留为NULL,它不会添加任何值吗? 这是怎么回事

写功能add如下方式

void add( node *head, int newData ) 
{
    node n = createNode( newData );

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

    *head = n;
}

或者你可以用下面的方式写

void add( node *head, int newData ) 
{
    while ( *head ) head = &( *head )->next;

    *head = createNode( newData );
}

并称它为

node test = NULL;

add( &test, 1 );
add( &test, 2 );
add( &test, 3 );

考虑到必须在函数add之前声明函数createNode并且您错过了结构定义中的分号

struct node {
    int data;
    node next;
}
^^^

同样,将相同的标识符用于结构标签和指向相同结构的指针也不是一个好主意。

typedef struct node* node;

至少写这样的东西会更好

typedef struct node* node_ptr;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM