0

I have a few questions regarding lists. First, here is my code:

#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

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

void main()
{
    node *root;
    node *curr;

    int exit = 0;
    string temp;
    root = new node;
    root->next = 0;
    curr = root;
    cout << "Please enter the root number: ";
    cin >> root->x;

    for( int i=0; i<10; i++)//Will promt user to enter numbers
    {
        cout << "Enter string name for new node: ";
        cin >> temp;
    }

    if (curr != 0)//Used for traversing the LL and outputting
    {
        while (curr->next != 0)
        {
            cout << curr->x;
            curr = curr->next;
        }
    }
}

I would like the user to be prompted to enter a number in the for loop to be added on to the first node. But I am confused on creating more nodes past the root. Do they have to have different names for each node? I see where I created a new node named root. Would I have to do that for each and every node? If I do, can I have the user input a name for that node and have the program write in that name?

4

1 に答える 1

1

To create more nodes past the root, just do the same thing:

 // assuming 'curr' points to end of list
 curr->next = new node;  // here's the new node
 curr = curr->next;      // update curr (if you want) to point to the newest node
 curr->next = 0;         // probably should be done in nodes ctor

You would not "name" the new nodes, you just have "root" and "curr". To find any one node, start at "root" and traverse to the one you want. Of course you could save ptrs to some nodes for faster access, but that would be specific to a particular application.

Also in your current input loop:

for( int i=0; i<10; i++)//Will promt user to enter numbers
{
    cout << "Enter string name for new node: ";
    cin >> temp;
}

The user inputs a value 10 times, but it goes in 'temp' every time. So it keeps getting overwritten.

于 2012-11-07T19:58:49.490 に答える