简体   繁体   中英

Linked list traversing in c

In the main function, I make a node with n = 50 and next = NULL . When I add a 10 to the linked list, although it has been added, it does not show up when traversing. The reason why that happens is because the start pointer that points to the node with 50 is not updated to point to the new node with 10 when add function is called. (line 28 to line 34).

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

typedef struct node
{
    int n;
    struct node* next;
} node;

void traverse(node* start)
{
    while(true)
    {
        printf("%i\n",start->n);
        start = start->next;
        if(start == NULL)
        {
            break;
        }
    }
}

void add(int num, node* start)
{
    node* previous = NULL;
    node* current = start;
    if(num<current->n)
    {
 //------------------------------------------------------------------------------

        //The problem is inside this if block.
        node* tmp = malloc(sizeof(node));
        tmp->next = current;
        current = tmp;
//-------------------------------------------------------------------------------

    }
    else
    {
        while(true)
        {
            previous = current;
            current = current->next;
            if(current == NULL)
            {
                node *tmp = malloc(sizeof(node));
                tmp->n = num;
                tmp->next = NULL;
                previous->next = tmp;
                break;
            }
            else
            {
                if(current->n > num)
                {
                    node *tmp = malloc(sizeof(node));
                    tmp->n = num;
                    tmp->next = current;
                    previous->next = tmp;
                    break;
                }
            }
        }
    }
}
int main(void)
{
    node* start = malloc(sizeof(node));
    start->n = 50;
    start->next = NULL;
    add(10,start);
    traverse(start);
}

How can I solve this problem?

You need to pass start as pointer to pointer in the add function so that you can modify it exactly in the place you have indicated. Declaration should look something like void add(int num, node** start) .

Also you should take care to free the memory allocated for the list before the end of the program.

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