Thanks for your help everyone. I see that C is going to challenge me a lot . I have implemented the suggested changes and think I now have a working solution. If nothing else I have learnt that I have much to learn.
Code:
#include <stdio.h>
#include <stdlib.h>
/*the node structure*/
struct node
{
struct node *next;
int x;
};
/*Globol Variables*/
struct node *lastNode = NULL;
void createNewNode(int xIn, struct node *root)
{
/*create a pointer and gift it some memory for the new node*/
struct node *element = malloc(sizeof(*element));
if(!element) /*check the memory allocation took place*/
{
printf("Out of memory");
exit(-1); /*exit program showing error code -1*/
}
findLastNode(root); /*find last node in list*/
if(!lastNode) /*if last node is null*/
{
/*inform the user of an error - in theory this should never happen*/
printf("The List needs a root or last node cannot be found");
exit(-1);
}
/*initialise the new node*/
element->next = NULL;
element->x = xIn;
/*set the previous node to point at this node*/
lastNode->next = element;
}
void findLastNode(struct node *startPoint)
{
/*loop until the next item is null i.e. this is the last node*/
while(startPoint->next!=NULL)
{
startPoint = startPoint->next; /*step forward*/
}
lastNode=startPoint; /*keep the globol lastNode up to date*/
}
void displayList(struct node *root)
{
if(root) /*if the root element exists*/
{
/*show the root element*/
printf("{addr}%d x[%d] n[%d]\n",root,root->x,root->next);
/*continue to show remaining elements until no more left*/
while(root->next!=NULL)
{
root = root->next; /*set the pointer to the next node in chain*/
printf("{addr}%d x[%d] n[%d]\n",root,root->x,root->next);
}
}
else
{
/*no root record so no list*/
printf("Nothing to show");
}
}
struct node *deleteList(struct node *startPoint)
{
struct node *tempNode; /*create pointer to store pointer between operations*/
do /*loop until curent node is NULL i.e. no more left*/
{
tempNode = startPoint->next; /*store current address before its deleted*/
free(startPoint); /*free up memory - delete node*/
startPoint=tempNode; /*reset the startPoint with backup before next iteration*/
}while(startPoint!=NULL);
tempNode=NULL; /*clean up*/
lastNode=NULL; /*clean up*/
return NULL; /*kill the root node by sending NULL*/
}
int main(int args, char *argv[])
{
/*create a pointer to root node and gift it some memory*/
struct node *root = malloc(sizeof(*root));
int x = 0; /*counter variable*/
/*test memory is assigned to root pointer*/
if(!root)
{
printf("Memory Error");
exit(-1);
}
/*initialise the root element*/
root->next = NULL;
root->x = 0;
/*add some more elements to the list*/
for(x = 1 ; x < 11 ; x++)
{
createNewNode(x,root);
}
/*display the total list*/
displayList(root);
/*delete the whole list*/
root = deleteList(root); /*delete list always returns NULL*/
/*display the total list*/
displayList(root);
/*free up the memory used by the root pointer*/
free(root);
return 0;
}