You are on page 1of 6

Doubly Link List

============================================
#include <iostream.h>

struct node {
node *back;
int data;
node* next;
};

class DoublyList {

public :
DoublyList () { h=t=NULL;}

void addTail(int d) {
if (isEmpty()){
h=new node;
t=h;
t->data=d;
t->next=NULL;
h->back=NULL;
}
else {
node *c=new node;
c->data=d;
t->next=c;
c->back=t;
t=c;
t->next=NULL;
}

}
void addHead(int d) {
if (isEmpty()){
h=new node;
t=h;
h->data=d;
h->back=NULL;
t->next=NULL;

}
else{
node *c=new node;
c->data=d;
c->next=h;
h->back=c;
h=c;
h->back=NULL;
}

bool removeTail(int &x) {


if (!isEmpty()){
if (h==t){
x=t->data;
delete t;
h=t=NULL;
return true;
}
else
{ node *c=t->back;

x=t->data;

delete t;
t=c;
t->next=NULL;
return true;
}//end else
}// end if
else

return false;

}
bool removeHead(int &x) {
if (!isEmpty()){
if (h==t){
x=h->data;
delete h;
h=t=NULL;
return true;
}
else
{ node *c=h;
x=h->data;
h=h->next;
delete c;
h->back=NULL;
return true;
}//end else
}// end if
else

return false;}

void insert(int value){


if(isEmpty()||value<h->data)
addHead(value);
else if(value>t->data)
addTail(value);
else
{
node *c=h;
node *d=new node;
d->data=value;
while(c->next->data<value)
c=c->next;
d->next=c->next;
c->next=d;
}

void insert2(int value){


if(isEmpty()||value<h->data)
addHead(value);
else
{
node *c=h,*p=NULL;
while((c!=NULL)&&(value >c->data))
{
p=c;
c=c->next;
}
node *d=new node();
d->data=value;
d->next=p->next;
p->next=d;
if(c==NULL)
t=d;
}

bool remove(int value){


if(isEmpty())
return false;
else if (h==t)
{
if(value==h->data)
{
delete h;
h=t=NULL;
return true;
}
else
return false;
}
else if(value==h->data)
{
removeHead(value);
return true;
}
else
{
node *c=h;
node *p;
while((c->next!=NULL&&(c->next->data!=value)))
c=c->next;
if(c->next==NULL)
return false;
else
p=c->next;
c->next=c->next->next;
delete p;
return true;
}

}
bool RemovedIndex(int index){
int i=0;
if(isEmpty())
return false;
else
{
if(index==0)
removeHead(index);
else
{
node *p=NULL;
node *c=h;
while((c!=NULL)&&(i!=index)){
p=c;
c=c->next;
i++;
}
if(c==NULL)
i--;
if(i!=index)
return false;
else if(c!=NULL){
p->next=c->next;
delete c;
return true;
}
}
}
return true;
}
void print (){
node *c;
c=t;
while(c!=NULL){
cout<<c->data<<endl;
c=c->next;
}
}

bool isEmpty() { return h==NULL;}


private:
node *h;
node* t;
};
void main () {

DoublyList ls;
ls.addHead(10);
ls.addTail(20);
ls.addTail(30);
ls.insert(5);
ls.print();
}

http://www.ravianeducation.blogspot.com
FARHAN: 03008855006

You might also like