Doubly Linked List:
A doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes.
This is a doubly-linked list program in C++:
#include<iostream>
using namespace::std;
class item{
public:
int key;
float data;
item* next;
item* prev;
item(int k,float d){
key=k;
data=d;
next=NULL;
prev=NULL;
}
void display(){
cout<<"Key Is : "<<key<<" & Data Is : "<<data<<endl;
}
};
class linkedList{
private:
item* tail;
item* head;
public:
linkedList(){
head=NULL;
tail=NULL;
}
void insertAtTail(item* i)
{
if(head==NULL)
{
head=i;
tail=i;
}
else{
item* curr=head;
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=i;
i->prev=curr;
tail=tail->next;
}
}
void insertAtHead(item* i)
{
if(head==NULL)
{
head=i;
}else{
i->next=head;
head->prev=i;
head=i;
}
}
void displayList()
{
if(head==NULL)
cout<<"List Is Empty ! "<<endl;
else{
item* curr=head;
cout<<"\t\t*** => Displaying List : "<<endl<<endl;
while(curr!=NULL)
{
curr->display();
curr=curr->next;
}
}
}
void delAtTail(){
cout<<"\t\t\t***** After Del At Tail *****"<<endl<<endl;
item* curr=tail;
tail=tail->prev;
tail->next=NULL;
curr->prev=NULL;
delete curr;
}
void delAtHead(){
cout<<"\t\t\t********** After Delete At Head **********"<<endl<<endl;
item* curr=head;
head=head->next;
head->prev=NULL;
delete curr;
}
void displayFromHead(){
if(head==tail)
{
cout<<"List is empty !"<<endl;
}else{
cout<<"\t\t\t********** Displaying From Head To Tail **********"<<endl<<endl;
item* curr=head;
while(curr!=NULL)
{
curr->display();
curr=curr->next;
}
}
}
void displayFromTail(){
if(head==tail)
{
cout<<"List is empty !"<<endl;
}else{
cout<<"\t\t\t********** Displaying From Tail To Head **********"<<endl<<endl;
item* curr=tail;
while(curr!=NULL)
{
curr->display();
curr=curr->prev;
}
}
}
};
int main()
{
linkedList *list=new linkedList();
list->insertAtTail(new item(3,4.5));
list->insertAtTail(new item(1,2.3));
list->insertAtTail(new item(4,5.6));
list->insertAtTail(new item(2,3.4));
list->displayList();
list->delAtTail();
list->displayList();
list->delAtHead();
list->displayList();
list->displayFromHead();
list->displayFromTail();
list->displayList();
}
No comments:
Post a Comment