Write a function to randomly delete a node in a doubly circular link list. The return type of this function
is void, and it will not accept any parameter. Then write a main() program to test your code. Here is
the sample output of the program.
Initial doubly link list is:
40 50 10 30 65 18 72
The computer has randomly chosen node number 5 to delete
The link list after deletion of node is
40 50 10 30 18 72
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Node{
public:
int data;
Node *next, *prev;
Node();
Node(int);
};
Node::Node(){
next = NULL;
prev = NULL;
}
Node::Node(int data){
this->data = data;
next = NULL;
prev = NULL;
}
class DoublyLinkedList{
Node *head, *tail;
int size;
public:
DoublyLinkedList();
void insert(int);
void remove(int);
void show();
int length(){return size;}
};
DoublyLinkedList::DoublyLinkedList(){
head = NULL;
tail = NULL;
size = 0;
}
void DoublyLinkedList::insert(int data){
if(head == NULL){
head = new Node(data);
tail = head;
size++;
}
else{
tail->next = new Node(data);
tail->next->prev = tail;
tail = tail->next;
size++;
}
}
void DoublyLinkedList::remove(int pos){
if(head != NULL){
int i = 0;
Node *temp = head;
while(temp != NULL && i < pos){
temp = temp->next;
i++;
}
if(pos > size - 1) return;
if(pos == 0){
head = head->next;
head->prev = NULL;
size--;
delete temp;
return;
}
if(pos == size - 1){
tail = tail->prev;
tail->next = NULL;
size--;
delete temp;
return;
}
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
size--;
delete temp;
}
}
void DoublyLinkedList::show(){
Node* curr = head;
while(curr != NULL){
cout<<curr->data<<" ";
curr = curr->next;
}
cout<<endl;
}
DoublyLinkedList list;
void removeRandom(){
int size = list.length();
int position = rand() % size;
cout<<"The computer has randomly chosen node number "<<position + 1<<" to delete\n";
list.remove(position);
}
int main(){
srand(time(NULL));
list.insert(40);
list.insert(50);
list.insert(10);
list.insert(30);
list.insert(65);
list.insert(18);
list.insert(72);
cout<<"Initial doubly link list is: \n";
list.show();
removeRandom();
cout<<"The link list after deletion of node is: \n";
list.show();
return 0;
}
Comments
Leave a comment