Implement a Linked List (LL) discussed above
including following operations.
◼ Insertion of node at any place in LL.
◼ Deletion of node at any place in LL
◼ Searching for a node at any place in LL
◼ Printing whole Linked List (LL)
◼ Checking emptiness of the LL
#include <iostream>
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 LL{
static Node *head, *tail;
int size;
public:
LL();
void insert(int, int);
void remove(int);
void print();
bool search(int);
bool empty();
};
Node* LL::head = NULL;
Node* LL::tail = NULL;
LL::LL(){
size = 0;
}
void LL::insert(int data, int index){
Node *temp = new Node(data);
Node *curr = head;
if(index == 0){
temp->next = head;
head = temp;
return;
}
for(int i = 0; i < index - 1; i++){
curr = curr->next;
}
temp->next = curr->next;
curr->next = temp;
size++;
}
void LL::remove(int data){
Node* curr = head;
Node* prev = NULL;
Node* temp = NULL;
while(curr != NULL){
if(curr->data == data){
if(prev == NULL){
temp = head;
head = head->next;
curr = head;
delete temp;
size--;
}
else{
temp = curr;
if(curr->next != NULL){
prev->next = curr->next;
}
else{
prev->next = NULL;
}
curr = curr->next;
delete temp;
size--;
}
}
else{
prev = curr;
curr = curr->next;
}
}
}
void LL::print(){
Node* curr = head;
while(curr != NULL){
cout<<curr->data<<" ";
curr = curr->next;
}
cout<<endl;
}
bool LL::search(int data){
LL list;
Node* curr = head;
while(curr != NULL){
if(curr->data == data) return true;
curr = curr->next;
}
return false;
}
bool LL::empty(){
return this->head;
}
Comments
Leave a comment