Linked Lists 303
while (head != NULL)
4
{5
printf("%d", head -> value);6
head = head -> next;7
}8
printf(" ");9
}10
11
static void List_print2Help(Node * head)12
{13
if (head == NULL)14
{15
return ;16
}17
printf("%d", head -> value);18
List_print2Help(head -> next);19
}20
21
void List_print2(Node * head)22
{23
printf("nPrintthewholelist: ");24
List_print2Help(head);25
printf(" ");26
}27
List print2 is the recursive function. It prints the message and then calls a helper
function. The helper function goes through the nodes one by one until reaching the end of
the list.
18.7 Destro ying a Linked List
List destroy destroys the whole list, releasing the memory for each node. The non-
recursive method keeps a pointer p for the node after the node to be deleted. The recursive
method uses the call stack to keep the value of head. Note that line 18 must be after line
17 because head -> next does not exist after free (head).
void List_destroy(Node * head)
1
{2
while (head != NULL)3
{4
Node * p = head -> next;5
free (head);6
head = p;7
}8
}9
10
void List_destroy2(Node * head)11
{12
if (head == NULL)13
304 Intermediate C Programming
{
14
return ;15
}16
List_destroy2(head -> next);17
free (head); // must be after the recursive call18
}19
The following main function shows how to use the linked list functions we have developed
in this chapter.
// file: main.c
1
#include "list.h"2
#include <stdlib.h>3
#include <stdio.h>4
int main(int argc , char * argv[])5
{6
Node * head = NULL; /* must initialize it to NULL */7
head = List_insert(head, 917);8
head = List_insert(head, -504);9
head = List_insert(head, 326);10
List_print(head);11
head = List_delete(head, -504);12
List_print(head);13
head = List_insert(head, 138);14
head = List_insert(head, -64);15
head = List_insert(head, 263);16
List_print(head);17
if (List_search(head, 138) != NULL)18
{19
printf("138isinthelist ");20
}21
else22
{23
printf("138isnotinthelistn");24
}25
if (List_search(head, 987) != NULL)26
{27
printf("987isinthelist ");28
}29
else30
{31
printf("987isnotinthelistn");32
}33
head = List_delete(head, 263); // delete the first Node34
List_print(head);35
head = List_delete(head, 917); // delete the last Node36
List_print(head);37
List_destroy(head); // delete all Nodes38
return EXIT_SUCCESS;39
}40
The output of this program is:
Linked Lists 305
insert 917
insert -504
insert 326
Print the whole list:
326 -504 917
delete -504
Print the whole list:
326 917
insert 138
insert -64
insert 263
Print the whole list:
263 -64 138 326 917
138 is in the list
987 is not in the list
delete 263
Print the whole list:
-64 138 326 917
delete 917
Print the whole list:
-64 138 326
This page intentionally left blankThis page intentionally left blank
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset