My favorite, Linked lists. I wrote this a few years
ago while learning C.
//*****************************
struct structure
{
// This line contains the data that this
// container carries.
char textline [81];
// This is the link to the next node.
struct structure *nextptr;
};
//these are aliases for the buffer structure.
typedef struct structure STRCT;
typedef STRCT *PTR;
// The pointer *PTR is the pointer that is used
// to declare any new nodes.
//*****************************
//variable declarations.
PTR ptr;
PTR savedptr;
PTR headptr;
PTR wrkptr;
//////////////////////////////////////////////
// The function allocats the memory for the new node.
STRCTPTR Add_Node (void)
{
//*********************************
#ifdef testrun
Application->MessageBox("Add_Node ();\n\nAdding new node.",
"DEBUG ", MB_OK);
#endif
//*********************************
TXTPTR newptr = new structure;
//******************************************
//Initializes the structure.
newptr->textline [0] = NULL;
newptr->nextptr = NULL;
//******************************************
//Return the pointer to the new node created.
return newptr;
}
//////////////////////////////////////////////
// Nuff said.
void Delete_Node (void)
{
//*********************************
#ifdef deletenode
Application->MessageBox
("delete_node ();\n\nDeleting entry from memory.", "DEBUG ",
MB_OK);
#endif
//*********************************
// The ptr is the first entry in the list. The ptr is
// incremented to the nextptr to reestablish the start of the list.
if (ptr == headptr)
{
headptr = ptr->nextptr;
delete ptr;
}
//The object to delete is inside the list.
else
{
// Go through the list and compare the title to the ptr->field.
for (wrkptr = headptr; wrkptr->nextptr != NULL; wrkptr =
wrkptr->nextptr)
{
// Here the determinating status is found
// to halt the loop and delete the appropriate node.
if (!strcmp (title, wrkptr->textline))
{
savedptr->nextptr = wrkptr->nextptr;
delete wrkptr;
wrkptr = NULL;
break;
}
else
{
// Save address of object before object to delete.
// The saved ptr is either declared at the beginning
// of the function or is a global.
savedptr = wrkptr;
}
}
}
}
//////////////////////////////////////////////
// Clears any list resident in memory.
void clear_linked_list (void)
{
PTR nextptr;
//******************************************
ptr = headptr;
if (ptr != NULL)
{
while (ptr != NULL)
{
nextptr = ptr->nextptr;
free (ptr);
ptr = nextptr;
}
//Free the last ptr.
free (ptr);
headptr = NULL;
}//end of if.
//******************************************
}