Query:
Write the code which takes two values from the user. Search them in the Doubly Linked List and delete those values from the linked list.
Solution:
First, we will define a user-specified data type with the keyword "struct". This struct data type will contain a data part, and two pointers to store the address. Then we will make some functions to proceed with our program. The "Create () " function will create a new node, get the data from the user and store it in our node. It will also set and keep the addresses of the next and previous nodes. In the same way, we will create a delete function to delete the nodes. In the main program, we will just call our functions and it will process it to give us an output.
Code:
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *head;
void create(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
cout<<"\nOVERFLOW\n";
}
else
{
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
cout<<"Node Inserted\n";
}
}
void delete_specified( )
{
struct node *ptr, *temp;
int val;
cout<<"Enter the value to be deleted: ";
cin>>val;
temp = head;
while(temp -> data != val)
temp = temp -> next;
if(temp -> next == NULL)
{
cout<<"Can't delete\n";
}
else if(temp -> next -> next == NULL)
{
temp ->next = NULL;
cout<<"Node Deleted\n";
}
else
{
ptr = temp -> next;
temp -> next = ptr -> next;
ptr -> next -> prev = temp;
free(ptr);
cout<<"\nNode Deleted";
}
}
int main ()
{
int a,b,c,d,e;
cout<<"Enter values: "<<endl;
cin>>a;
create(a);
cin>>b;
create(b);
cin>>c;
create(c);
cin>>d;
create(d);
cin>>e;
create(e);
cout<<endl;
delete_specified( );
return 0;
}