add linked list item to the top
ive been at this for a while now trying to understand the logic of adding an item to the top/beginning of a linked list.
Code:
//////////////////////////////////////////
struct link //one element of list
{
int data; //data item
link* next; // pointer to the next link
};
////////////////////////////////////////////
void linklist::additem(int d) //add item
{
link* newlink = new link; //make a new link
newlink->data = d; //give it data
newlink->next = dummy; //it points to the next link
dummy = newlink; //now dummy points to this
}
void linklist::display() //display all links
{
link* current = dummy; //set ptr to dummy link
while( current != NULL ) //quit on last link
{
cout << current->data << endl; //print data
current = current->next; //move to next link
}
}
dummy is set to null in the constructor. now, in a previous thread, i got the concept of whats going on here. dummy points to the newest link and when the program outputs the display() it basically has the 'LIFO' output just like a stack. what i want is for it to be 'FIFO' (first in-first out). im not asking for code to fix this, just a hint in the right direction. thanks in advance.
edit:
the exercise in my book says to only revise the additem().