forked from Vishal-Aggarwal0305/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList_6_deletelist.c
60 lines (47 loc) · 1.08 KB
/
linkedList_6_deletelist.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdlib.h>
// A Linked List Node
struct Node
{
int data;
struct Node* next;
};
// Helper function to create a new node with the given data and
// pushes it onto the list's front
void push(struct Node** head, int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
// Recursive function to delete a linked list
void deleteList(struct Node** head)
{
if (*head == NULL) {
return;
}
if ((*head)->next) {
deleteList(&((*head)->next));
}
printf("Deleting %d\n", (*head)->data);
free(*head);
*head = NULL;
}
int main(void)
{
// input keys
int keys[] = { 1, 2, 3, 4, 5 };
int n = sizeof(keys) / sizeof(keys[0]);
// points to the head node of the linked list
struct Node* head = NULL;
// construct a linked list
for (int i = n - 1; i >= 0; i--) {
push(&head, keys[i]);
}
deleteList(&head);
if (head == NULL) {
printf("List deleted");
}
return 0;
}