简体   繁体   中英

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.

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:

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:

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. But if I leave the test node to be NULL, it doesn't add any values? What is happening here?

Write function add the following way

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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