My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

implement "bool find(int)" function for DoublyLinkList)

Umer khan's photo
Umer khan
·Jun 9, 2020

#include <iostream>

#include <stdlib.h>

#include <stdio.h> using namespace std; //Node Class class Node { private: int data; Node next, prev; public: int get(){ return data; } void set(int a){ data = a; }

Node* getNext(){
    return next;
}
void setNext(Node *x){
    next = x;
}

Node* getPrev(){
    return prev;
}
void setPrev(Node *x){
    prev = x;
}

};

//Doubly Link List Class class DList { private: Node head, current; int size; public: // Constructor DList(){ head = current = NULL; size = 0; } // add function void add(int x){ Node newNode = new Node(); newNode->set(x);
if( head == NULL ){ head = current = newNode; newNode->setNext(NULL); newNode->setPrev(NULL); } else{ if(current->getNext()==NULL){ newNode->setNext(NULL); } else{ newNode->setNext(current->getNext()); (current->getNext())->setPrev(newNode); } current->setNext(newNode); newNode->setPrev(current); current = newNode; } size++; } // get Function int get(){ if (current != NULL) return current->get(); } // next Function void next(){ if (current != NULL && current->getNext() != NULL){ current = current->getNext(); } } // remove Function void remove(){ if( size>0 ){ if( current == head ){ //if its the 1st Node of List head = head->getNext(); head->setPrev(NULL); delete current; current = head; } else if( current->getNext() != NULL ){ //if its the any central node of List Node
temp = current; (current->getPrev())->setNext(current->getNext()); (current->getNext())->setPrev(current->getPrev()); current = current->getNext(); delete temp; } else if( current->getNext() == NULL ){ //if its the last node of the List current = current->getPrev(); delete current->getNext(); } size--; } else{ cout<<"List is Empty\n"; }
} //display Function void display(){ Node temp = head; for (int i=1; i<=size; i++){ cout<<temp->get()<<", "; temp = temp->getNext(); } cout<<endl; } // start Function void start(){ current = head; } // findRemoveDuplicate Function /void findRemoveDuplicate(){ Node temp1 = head, temp2, prev; cout<<"Duplicate: "; while(temp1 != NULL){ temp2 = temp1->getNext(); prev = temp1; while(temp2 != NULL){ if(temp1->get() == temp2->get()){ cout<<temp2->get()<<", "; prev->setNext(temp2->getNext()); temp2->setNext(NULL); delete(temp2); temp2 = prev->getNext(); size--; } else{ temp2 = temp2->getNext(); prev = prev->getNext(); } } temp1 = temp1->getNext(); } cout<<"\nNOTE: Setting current pointer to the start after removing duplicates\n"; start(); }/ };

//Main Function main(){ DList l1; int x; // adding data for (int i=1; i<=5; i++){ cout<<"Enter Data for Node "<<i<<endl; cin>>x; l1.add(x); }

cout<<"List is: \n";
l1.display();

}