简体   繁体   中英

adding nodes into singly-linked list

I am trying to learn linked lists.I just wrote a program illustrating a linked list but it doesn't seem to work.Here's the code:

#include <iostream>
using namespace std;

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

int main(int argc, const char * argv[])
{
    node* trav;
    node* root;
    root = new node;

    trav = root;

    trav -> data = 4;
    trav -> next = new node;

    trav -> data = 5;
    trav -> next = new node;

    trav -> data = 6;
    trav -> next = 0;
    trav = root;

    while (trav!=0) {
        std::cout<<trav->data;
        trav=trav->next;
    }
}

I want root to point to the first node but it seems to copy trav 's data as we go further into the program. Any idea what's wrong?
Thanks

In this code:

trav = root;

trav -> data = 4;
trav -> next = new node;

trav -> data = 5;
trav -> next = new node;

you are not changing the trav pointer, which means you are overwriting its members. After creating new node by calling trav->next = new node; you should "move" to the next node by calling:

trav = trav-> next;

You never do

trav = trav -> next;

When you fill up the list. You don't move in the list, and just keep modifying the root.

You are missing trav = trav -> next after trav -> next = new node ; in other words, you create a new node but you never actually "step" there.

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