简体   繁体   English

指针C链表添加总是NULL

[英]Pointers C Linkedlist Adding Always NULL

I've written a function for adding to the end of a singly linked list in C. But what I don't get is why if the head element is NULL, why it continues remaining to be NULL after successive adds. 我已经编写了一个函数,用于在C中添加到单链表的末尾。但是,我没有得到的是为什么head元素为NULL,为什么在连续添加后它仍保持为NULL。

The struct is defined as this: 该结构定义如下:

typedef struct node* node;

struct node {
    int data;
    node next;
}

In the main I have this: 总的来说,我有这个:

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

function add is defined as such: 函数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 is defined as thus: createNode的定义如下:

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

What I am confused about is that, the add function works fine if I first initialize the head (node test = createNode(1)) and then proceeds to add the rest of the values alright. 我感到困惑的是,如果我首先初始化head(节点test = createNode(1)),然后继续添加其余值,那么add函数就可以正常工作。 But if I leave the test node to be NULL, it doesn't add any values? 但是,如果我将测试节点留为NULL,它不会添加任何值吗? What is happening here? 这是怎么回事

Write function add the following way 写功能add如下方式

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

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

    *head = n;
}

or you can write even the following way 或者你可以用下面的方式写

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

    *head = createNode( newData );
}

and call it like 并称它为

node test = NULL;

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

Take into account that function createNode must be declared before function add and you missed a semicolon in the structure definition 考虑到必须在函数add之前声明函数createNode并且您错过了结构定义中的分号

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

Also it is not a good idea to use the same identifier for a struture tag and pointer to the same structure 同样,将相同的标识符用于结构标签和指向相同结构的指针也不是一个好主意。

typedef struct node* node;

At least it would be better to write something like 至少写这样的东西会更好

typedef struct node* node_ptr;

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

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