Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 3
Data Structure help
I understand how to set up the list but how do I output values that I entered into the list? #include <iostream> using namespace std; struct node { int data; node *next;///pointer next to point to next node }; node *AddNode(node *plist) ///function takes list pointer { node *n=new node;///create new node cout<<"Enter value into node: "; cin>>n->data;///enter data value n->next=plist;///accessing next pointer to point to list plist=n;///list now holds the new node return plist; } int main() { node *plist; int num; cout<<"Enter how many nodes: "; cin>>num; for(int i=0; i<num; i++) { AddNode(plist); } cout<<"Output: "<<endl; for(int i=0; i<num; i++) { cout<<plist->data<<endl; } }
5 Answers
+ 3
Baptiste I tried to follow more or less the same which you posted but I couldn't got your code. Anyway I tried and we never get correct value.
Please, could you write a complete code to see that working?
Thanks.
+ 2
Great! but show result in inverse order
+ 2
it is because addNode add values at the beginning of the list, I can do a complete list structure in C or C++ if you want but I used the code given by @Chris :)
+ 1
https://code.sololearn.com/c9va259r6n3x/?ref=app
I had to correct two more things
plist has to be initialized to 0, NULL or nullptr
AddNode result has to be saved in plist
0
node * tmp = plist;
while(tmp){
cout << tmp ->data << endl;
tmp = tmp->next;
}