This is the basic idea:
Code:
struct Node
{
struct Node * next;
int value;
};
struct Node * AllocNode(int initial)
{
struct Node * node = (Node*)malloc(sizeof(struct Node));
if(node != NULL)
{
node->next = 0;
node->value = initial;
}
return node;
}
void DestroyList(struct Node ** root)
{
struct Node * next, * prev = *root;
while(prev != NULL)
{
next = prev->next;
free(prev);
prev = next;
}
*root = 0;
}
struct Node * AddNode(struct Node ** root, int value)
{
struct Node * next = *root;
struct Node * node = AllocNode(value);
if(*root != NULL)
{
while(next->next != NULL)
{
next = next->next;
}
next->next = node;
}
else
{
*root = node;
}
return node;
}
void PrintList(struct Node * root)
{
struct Node * next = root;
while(next != NULL)
{
printf("%d\n", next->value);
next = next->next;
}
}
int main()
{
struct Node * root = NULL;
AddNode(&root, 10);
AddNode(&root, 9);
AddNode(&root, 8);
AddNode(&root, 7);
PrintList(root);
DestroyList(&root);
return 0;
}