Data Structure help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; } }

14th Sep 2017, 11:11 PM
Chris
Chris - avatar
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.
15th Sep 2017, 6:50 AM
Daniel
Daniel - avatar
+ 2
Great! but show result in inverse order
15th Sep 2017, 4:06 PM
Daniel
Daniel - avatar
+ 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 :)
15th Sep 2017, 8:16 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 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
15th Sep 2017, 8:20 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
node * tmp = plist; while(tmp){ cout << tmp ->data << endl; tmp = tmp->next; }
15th Sep 2017, 4:51 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar