
Destroying All Nodes in a Linked List
Quote:
>Is it important that after DestroyList, *Head is null? Without knowing
>more about your list implementation, I can't tell, but you can always
>add a
> *Head = 0;
>as the last line of the above function.
I didn't want to paste all of the code to the news group, but if it would
help clarify what I'm doing then here it is (pasted at the bottom of the
message). All I am doing is creating a linked list of integers, displaying
that list, destroying the list, then trying to display it again (but it
shouldn't display the second time because it's empty and therefore it will
print an appropriate message). My question is the following: Is my
DestroyList correct? I ask because of the following:
(1) If I don't include the line *Head=NULL; (it's marked in the code as
"Line in Question") then when I try to print this list after destroying it
then it does actually print the list again.
(2) My concern is that I am not returning the memory to the heap properly
and that the list is considered "empty" only because I am assigning the
pointers to NULL.
Help is appreciated,
Derek Battams (** CODE FOLLOWS **)
#include <stdio.h>
#include <stdlib.h>
#define StringSize 255
typedef struct NodeTag
{
int AnInt;
struct NodeTag *Next;
Quote:
} Node;
void AddNodeToList (Node **, int);
void DisplayList (Node *);
void DestroyList (Node **);
void AddNodeToList (Node **Head, int Number)
{
Node *Current, *NewNode;
NewNode = malloc (sizeof(Node));
NewNode->AnInt = Number;
NewNode->Next = NULL;
if (*Head == NULL)
{
*Head = NewNode;
}
else
{
Current = *Head;
while (Current->Next != NULL)
Current = Current->Next;
Current->Next = NewNode;
}
return;
Quote:
}
void DisplayList (Node *Head)
{
Node *Current;
if (Head != NULL)
{
Current = Head;
while (Current != NULL)
{
printf ("%d\n", Current->AnInt);
Current = Current->Next;
}
printf ("Done displaying...\n");
}
else
printf ("Nothing to display, this list is empty!\n");
return;
Quote:
}
void DestroyList (Node **Head)
{
if ((*Head)->Next != NULL)
DestroyList (&((*Head)->Next));
free (*Head);
*Head = NULL; /* Line in question */
return;
Quote:
}
int main ()
{
char *String;
Node *Head;
int *Number;
Head = NULL;
String = malloc (sizeof(char) * StringSize);
Number = malloc (sizeof(int));
fgets (String, StringSize, stdin);
sscanf (String, "%d", Number);
while (*Number != 0)
{
AddNodeToList (&Head, *Number);
fgets (String, StringSize, stdin);
sscanf (String, "%d", Number);
}
printf ("\nHere are the numbers that you typed...\n");
DisplayList (Head);
if (Head != NULL)
DestroyList (&Head);
DisplayList (Head);
free (String);
free (Number);
return 0;
Quote:
}