So I am trying to program in C++ a linked list but I’m not sure how to do it exactly. I understand the concept more or less and I saw a tutorial that gave me this code but it didn’t explain it too well. I was wondering if you all could help me with the next steps, explain to me what I just did, and explain to me how to continue. I want it to add elements, pop or push elements in a stacked manner, last in first out, and free elements at the end and free up the memory to prevent memory leaks. thank you.
#include <iostream>
using namespace std;
struct node
{
int num;
node *link;
}*p;
void main()
{
node *root;
root = new node;
root->num=5;
root->link = p;
p = root;
node *q;
for(q = p; q != NULL; q = q->link)
{
cout<<q->num;
cout<<endl;
}
}
First of all, since you already use the standard library (
#include <iostream>), be informed that the standard library already have lists: (#include <list>) as well as other containers.You can find their documentation here
In case you want to write yourself, use a proper approach: don’t put everything into main, but define a proper class and methods to manipulate the elements. You can refer to the standard documentation I linked as a “inspiration”.
You will probably end-up with something like