here's an example of how a simple linked list works.
Code:
#include <iostream>
int main()
{
//use a prototype - it's needed for the pointer in the struct
struct link;
//define the prototype
struct link
{
//this is the payload
int data;
//this is the pointer to the next in the list
link*next;
};
//create a pointer to the "head" or first link in the list
link*head=new link;
//this is the pointer to the "current" link in the list
link*curr=head;
//this is the pointer to the "next" link in the list
link*next=0;
//fill the first link with null data
curr->data=-1;
//point the first link's pointer to nothing
curr->next=0;
//a simple for loop, creating 11 nodes
for(register short int i=0;i<12;i++)
{
//create a fresh node
next=new link;
//point the current link's pointer to that node
curr->next=next;
//move into the node
curr=next;
//fill it with data
curr->data=i;
//point it's pointer to nothing
curr->next=0;
}
//point the "current" pointer to the top of the list
curr=head;
//we're not going to need the "head" pointer anymore
head=0;
//this time we're going to read from the list and delete it
for(register short int i=0;i<12;i++)
{
//output what's in the current node (note we're printing the
//first node we filled with null input)
std::cout<<curr->data<<std::endl;
//set the "next" pointer to the next node in the list
//if this was the last node, it'll be pointing to nothing (0)
next=curr->next;
//delete this node
delete curr;
//move into the next node. If this was the last node, it
//assigns nothing (0) to the curr pointer.
curr=next;
}
//be nice.
return 0;
}
edit: I think that's right, but it's been a while since I've written a linked list, so if anybody catches any memory leaks or anything please speak up