In: Computer Science
C PROGRAMMING
Create the int delete(int key) function so that it deletes the LAST occurrence of a given number in the linked list
Make sure the parameter for this delete function is (int key).
Also, use these variables and global Nodes BELOW as this is a DOUBLY LINKED LIST!!!
#include
#include
typedef struct node
{
int data;
struct node *next;
struct node *prev;
} Node;
Node *head;
Node *tail;
-----------------------
So, the function has to look like this… !!! Write in “// code”
int delete (int key) {
// code
}
SOLUTION:
int delete(int key){
//since we are not taking the head as a parameter so we are reading
it from the global head
struct Node* temp=head,temp1=null;
//iterate through the linked list
while(*temp){
//check for the key
if(temp->data==key){
//if key found update the node address
temp1=temp;
}
//move onto the next node
temp=temp->next;
}
//intialy we have defined temp1 as null we are checking that wheher
an element found or not if found delete that node
if(temp1){
//get the node address of previous node of the deleting node
struct Node* tmp=temp1->prev;
//link the previous node next to the dele node next node so that
one side link will be established
tmp->next=temp1->next;
//for two side link we need to update the dele nodes next nodes
previous address by placing the deleting nodes previous
address
temp1->next->prev=tmp;
//free the deleting node
free(temp1);
}
return 0;
}