hears an example of what I am talking about
#include <stdio.h>
struct node_data /*first define your variables i'm using a C++ compiler so i dont need the type_def*/
{
char *data;
node_data *prev, *next;
};
struct node_handler
{
node_data *first, *current;
int node_count;
};
/*** note with these functions you are responsiable for creating or deleting the data ***/
node_data* push(node_handler *handle, node_data *data)
{
data->prev = data->next = NULL;
if (handle->node_count == 0)
{
handle->first = data;
} else {
data->prev = handle->current;
data->next = handle->current->next;
}
handle->current = data;
handle->node_count++;
return handle->current;
}
node_data* pop(node_handler *handle)
{
node_data* temp;
temp = handle->current;
if (temp == NULL)
return NULL;
if (temp->prev != NULL)
temp->prev->next = temp->next;
handle->current = temp->prev;
if (temp->next != NULL)
temp->next->prev = temp->prev;
handle->node_count--;
return temp;
}
/*this is a refrence of a way to cleanup, i didn't use this because i locally allocated everything for convience but you may need something like it*/
void cleanup_all(node_handler *handle)
{
node_data *currentnode, *nextnode;
if (handle->first != NULL)
currentnode = handle->first;
else if (handle->current != NULL)
currentnode = handle->current;
else
return;
while (currentnode->next != NULL)
{
nextnode = currentnode->next;
delete currentnode;
nextnode->prev = NULL;
currentnode = nextnode;
}
}
int main()
{
node_handler handle; /*create and fill your node handler function*/
handle.node_count = 0;
handle.first = NULL;
handle.current = NULL;
node_data one, two, three, *temp;
one.data = "This is the first node\n";
two.data = "This is the second node\n";
three.data = "This is the third node\n";
push(&handle, &one);
push(&handle, &two);
push(&handle, &three);
printf ("there are %d nodes stored\n", handle.node_count);
while (handle.node_count > 0) {
temp = pop(&handle);
if (temp != NULL)
printf( temp->data);
printf ("there are %d nodes stored\n", handle.node_count);
}
/*i did not need to delete anything because i allocated everything locally. EG: not using the new and delete or maloc or free*/
return 1;
}