# Program to Delete a Linked list

• Write a C program to delete a singly linked list.
• Write function in C to delete all nodes of a linked list.

To delete a linked list we need a pointer to the head node of linked list. We will write a function "deleteLinkedList" which takes head node of a linked list as input and deletes all nodes of given linked list one by one from head till tail node.

Singly linked list's node structure is as follows:
```struct node {
int data;
struct node *next;
}
```

Algorithm to delete all nodes of a linked list
Let "head" be the pointer to pointer of head nodes of linked list to be deleted.
• Using a while loop, we will traverse given linked list until (*head != NULL).
• We will store the head pointer in a temporary pointer variable "temp".
• Now, delete node pointed bu temp variable(free(temp)).
```void deleteLinkedList(struct node **head) {
struct node *temp;
while (*head != NULL) {
free(temp);
}
}
```

## C program to delete all nodes of a linked list

```#include <stdio.h>
#include <stdlib.h>

/* A structure of linked list node */
struct node {
int data;
struct node *next;

void initialize(){
}

/*
Given a Inserts a node in front of a singly linked list.
*/
void insert(int num) {
/* Create a new Linked List node */
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data  = num;
/* Next pointer of new node will point to head node of linked list  */
/* make new node as new head of linked list */
printf("Inserted Element : %d\n", num);
}

struct node *temp;
while (*head != NULL) {
free(temp);
}
}

/*
Prints a linked list from head node till tail node
*/
void printLinkedList(struct node *nodePtr) {
if(nodePtr == NULL)
while (nodePtr != NULL) {
printf("%d", nodePtr->data);
nodePtr = nodePtr->next;
if(nodePtr != NULL)
printf("-->");
}
}

int main() {
initialize();
/* Creating a linked List*/
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);

return 0;
}
```
Output
```Inserted Element : 8
Inserted Element : 3
Inserted Element : 2
Inserted Element : 7
Inserted Element : 9