hi
this is a program to perform insertions and deletion in doubly link list...
Operations in doubly link list using header->next
#include<iostream.h>
#include<conio.h>
class dll
{
struct dll_node
{
dll_node *prev,*next;
int data;
}*header,*first,*last,*nn;
public:
dll()
{
header=new dll_node;
header->data=0;
header->next=NULL;
header->prev=NULL;
last=NULL;
}
~dll()
void create(int);
void display();
void insertatbeg(int);
void insertatend(int);
dll_node* search(int);
void insertkey(int,int);
void insertbeforekey(int,int);
void deleteatbeg();
};
void dll::create(int k)
{
dll_node *nn;
for(int i=1;i<=k;i++)
{
nn=new dll_node;
nn->data=i*10;
nn->prev=NULL;
nn->next=NULL;
if(header->next==NULL)
header->next=last=nn;
else
{
nn->prev=last->next;
last->next=nn;
last=nn;
}
}
display();
}
void dll::display()
{
dll_node *ptr;
cout<<endl;
for(ptr=header->next;ptr!=NULL;ptr=ptr->next)
cout<<ptr->data<<"->";
}
void dll::insertatbeg(int d)
{
nn=new dll_node;
nn->data=d;
if(header->next==NULL)
{
nn->next=NULL;
nn->prev=header;
header->next=nn;
last=nn;
}
else
{
nn->prev=header;
nn->next=header->next;
header->next=nn;
nn->next->prev=nn;
}
display();
}
void dll::insertatend(int d)
{
nn=new dll_node;
nn->data=d;
if(last==NULL)
{
header->next=last=nn;
}
else
{
nn->next=NULL;
nn->prev=last->next;
last->next=nn;
last=nn;
}
display();
cout<<"last="<<last->data;
}
dll_node* dll::search(int key)
{
dll_node *ptr;
for(ptr=header->next;ptr->next!=NULL && ptr->data!=key;ptr=ptr->next);
if(ptr!=NULL)
cout<<"Key "<<ptr->data<<" found";
else
cout<<"key "<<key<<" not found";
return ptr;
}
void dll::insertbeforekey(int key,int d)
{
dll_node *ptr,*nn;
nn=new dll_node;
nn->data=d;
ptr=search(key);
if(ptr!=NULL)
{
nn->next=ptr;
nn->prev=ptr->prev;
ptr->prev=nn;
nn->prev->next=nn;
}
else
cout<<"Insertion failed";
display();
}
void dll::insertafterkey(int key,int d)
{
dll_node *ptr;
nn=new dll_node;
nn->data=d;
ptr=search(key);
if(ptr!=NULL)
{
nn->next=ptr->next;
nn->prev=ptr;
ptr->next=nn;
nn->next->prev=nn;
}
else
cout<<"Insertion failed";
cout<<"last="<<last->data;
display();
}
void dll::deleteatbeg()
{
dll_node *ptr;
ptr=header->next;
if(header->next==NULL)
cout<<"Deletion is not possible";
else
header->next=ptr->next;
delete ptr;
cout<<"last="<<last->data;
display();
}
int main()
{
clrscr();
dll d;
cout<<"Create:";
d.create(7);
cout<<"\n\nInsert at beg:";
d.insertatbeg(58);
cout<<"\n\nInsert at end:";
d.insertatend(74);
cout<<"\n\nInsert before key:";
d.insertbeforekey(40,9);
cout<<"\n\nInsert after key:";
d.insertafterkey(40,5);
cout<<"\n\ndelete at beg:";
d.deleteatbeg();
getch();
return 0;
}
}
griswolf 304 Veteran Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.