# Delete all Occurrence of the key from the given linked list

Delete all Occurrence of the key from the given linked list” is again one of the important problem asked in many technical interview based on linked list. Here, we are given a linked list and our task is to delete all occurrences of a given key ‘x’ from a linked list.

```For example, we need to delete all occurrences of ‘45’ from a given list.
List:   45 -> 55 -> 32 -> 45 -> 66 -> 71 -> 45 -> 33 -> 45
After deleting all occurrences of ‘45’, the list will become:
List:   55 -> 32 -> 66 -> 71 -> 33```

The steps required to Delete all Occurrence of the key from the given linked list is as follows:

1. Before traversing the complete linked list, we will delete all beginning occurrences of given key ‘x’ and adjust our head accordingly.
2. Now, after adjusting the head of the linked list, we will traverse the complete linked list and delete all occurrences of given key ‘x’ from a linked list.

C++ Program to Delete all Occurrence of the key from the given linked list is as follows:

```/* C++ Program to delete all occurrences of the given key from the Linked List */
#include<bits/stdc++.h>
using namespace std;

/* Structure of the node of the linked list */
typedef struct node
{
int data;
struct node *next;
}Node;

/* Function to Insert node at the end of the linked list */
void insert_end(Node **head, int ele)
{
/* Creating a new node */
Node *new_node;
new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = ele;
new_node->next = NULL;

/* check whether the linked list is empty or not */

/* If Linked List is empty, then new node will become head of the linked list */
{
return;
}

/* If Linked List is not empty, then traverse the complete linked list and point the pointer
of last node of the linked list to the new node */
Node *temp = NULL;
while(temp->next != NULL)
temp=temp->next;
temp->next = new_node;
}

/* Function to delete all occurrences of a given key from a linked list */
Node *deleteAllx(Node *head , int x)
{
/* If Linked List is empty, return head */

/* Delete All occurrences of the given key from the beginning, and adjust head accordingly */

/* Now, delete remaining occurrences of the key from the linked list by storing the previous
node and pointing it to desired location accordingly */
while(temp->next != NULL)
{
if(temp->next->data == x)
{
Node *p = temp->next;
temp->next=temp->next->next;
delete p;
}
else
{
temp=temp->next;
}
}
}

/* Function to Print the Linked List  */
{
Node *temp = head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
/* Inserting Some Nodes in the Linked List */
cout<<"Linked List before deleting all occurrences of 45:\n";
cout<<"\nLinked List after deleting all occurrences of 45:\n";
```OUTPUT: