简体   繁体   中英

Won't display more than one value

There is no error but I was expecting 10 values but I only got one. The below is my create and display function.

void create()
{
int random;
for (int i = 0; i < 10; i++)
{
    struct node *new_node, *current;
    new_node = new node;
    random = randomNum();
    new_node->data = random;
    new_node->next = NULL;
    if (start == NULL)
    {
        start = new_node;
        current = new_node;
        new_node = NULL;
    }
    else
    {
        current->next = new_node;
        current = new_node;
    }
 }
}

void display()
{
struct node *new_node;
new_node = start;
while (new_node != NULL)
{
    cout << new_node->data << "->";
    new_node = new_node->next;
}
}

What do I need to change?

Try the following line

current = new_node;    
current->next = new_node;

Because in your case there is no value of current pointer so how can you update its next. First of all update/set the current then update/set its next.

if (start == NULL)
    {
        start = new_node;
        current = new_node;
        current->next = NULL;
        new_node = NULL;
    }
    else
    {
        current = new_node;
        current->next = new_node;

    }

The problem with the compiler message is that the compiler is unable to determine whether the variable current used in the else statement was early initialized.

If it is a warning you may ignore it.

Or you can rewrite the function the following way

void create()
{
    const int N = 10;

    node **current = &start;

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

    for ( int i = 0; i < N; i++ )
    {
        *current = new node;
        ( *current )->data = randomNum();
        ( *current )->next = nullptr;
        current = &( *current )->next;
    }
 }

The body of the for loop can be also written like (I assume that the data member data precedes the data member next in the node definition. Otherwise exchange the initializers.

*current = new node { randomNum(), nullptr };
current = &( *current )->next;

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