#include <iostream>
using namespace std;
struct Node
{
int item; // storage for the node's item
Node* next; // pointer to the next node
};
Node* addNode(Node*& head, int data , int& count)
{
Node * q; // new node
q = new Node; // allocate memory for the new mode
q->item = data; // inserting data for the new node
q->next = head; // point to previous node ?? how would i do that? ( am i doing it correctly?)
count++; // keep track of number of node
head = q;
return q;
}
int main()
{
int a, count=0;
int data;
bool repeat;
Node *head= NULL;
//^^ assuming thats creating the first node ^^
do
{
cout << "please enter the data for the next node" <<endl;
cin >> data;
addNode(head, data, count);
cout << "do you wish to enter another node? (enter true or false)" << endl;
cin >>repeat;
}
while (repeat == true);
// assuming this is the print function
while(head != NULL)
{
cout << "output" << temp->item << endl;
cout << temp->next << endl;
}
system("pause");
return 0;
}
okey i tried adding a new element in the list how would i move the head around like a LIFO memory (stack) so the last element is on the very top..
any help would be appreciated ! The pointers and the nodes are messing with my brain lately ….
Since I’m not sure every answer completely answers it, here’s a linked list implementation (written without testig:
Now we need two pointers somewhere to look after the list:
Now we need to create some elements. As others have said, you can do that with new:
Notice how I didn’t try to add these elements to a list yet? That’s because I’ve got a function in mind which looks like this:
You can call this by doing this:
Deleting elements is somewhat more tricky, since you have to go to that element, remember its previous element, grab it’s next element, join them up and delete the Node* you’re on.
Now for traversing lists… your terminology
HEAD|TAILreminds me of Erlang and tail recursion, where the current element is referred to as the head and the remainder the tail. If I write:You can see this happening. Replacing
curwithheadhere would be harmless thanks to theListstruct.Finally, I’ve used a very C-like approach here, but there’s scope for templates:
and encapsulating the
Liststruct as a class:Which brings you a little bit closer to
std::list.