Saturday, 26 November 2016

Double Linked list


Header file
#ifndef _DOUBLELINKEDLIST_
#define _DOUBLELINKEDLIST_
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *prev,*next;
};
class doublelinkedlist
{
private:
Node *first;
public:
doublelinkedlist();
void insetfirst(int);
void deletefirst();
void print();
bool isEmty();
void makeEmpty();
~doublelinkedlist();
void deletelast();
void append(int);
};
#endif

Cpp File

#include "doublelinkedlist.h"
doublelinkedlist::doublelinkedlist()
{
first=NULL;
}
void doublelinkedlist::insetfirst(int val)
{
Node *temp=new Node;
temp->data=val;
if (isEmty())
{
temp->next=NULL;
temp->prev=NULL;
first=temp;
}else
{
temp->prev=NULL;
temp->next=first;
first->prev=temp;
first=temp;
}
}
void doublelinkedlist::print()
{
if (isEmty())
{
cout <<"their is no node to display"<<endl;
}else
{
Node *temp=first;
while (temp!=NULL)
{
cout <<temp->data<<endl;
temp=temp->next;
}
}

}
bool doublelinkedlist::isEmty()
{
return first==NULL;
}
void doublelinkedlist::makeEmpty()
{
if (!isEmty())
{
Node *temp;
while (first!=NULL)
{
temp=first;
first=first->next;
delete temp;
}

}
}
doublelinkedlist::~doublelinkedlist()
{
makeEmpty();
}
void doublelinkedlist::deletefirst()
{
if (isEmty())
{
cout <<"Their is no node to delete "<<endl;
}
else if (first->next==NULL)
{
first=NULL;
}else
{
Node *temp=first;
first=temp->next;
first->prev=NULL;
delete temp;
}
}
void doublelinkedlist::deletelast()
{
if (!isEmty())
{
Node *temp=first;
while(temp->next!=NULL)
{
temp=temp->next;
}
if (first==temp)
{
deletefirst();
}else
{
temp->prev->next=NULL;
delete temp;
}
}
}
void doublelinkedlist::append(int val)
{
if (isEmty())
{
insetfirst(val);
}else
{
Node *temp=new Node,*ptr=first;
while (ptr->next!=NULL)
{
ptr=ptr->next;
}
temp->data=val;
ptr->next=temp;
temp->prev=ptr;
temp->next=NULL;
}
}


Main

#include "doublelinkedlist.h"
int main ()
{
doublelinkedlist d;
cout <<"Inset first "<<endl;
d.insetfirst(0);
d.insetfirst(1);
d.insetfirst(2);
d.print();
cout <<"calling make Empty "<<endl;
d.makeEmpty();
d.print();
cout <<"delete first "<<endl;
d.insetfirst(0);
d.insetfirst(1);
d.insetfirst(2);
cout <<"Before delete  "<<endl;
d.print();
cout <<"After delete  "<<endl;
d.deletefirst();
d.print();
cout <<"Delete last "<<endl;
d.deletelast();
d.print();
cout <<"Using append function "<<endl;
d.append(7);
d.print();
return 0;
}

No comments: