Opeartions on Doubly Lined List

 

#include<iostream>
#include<stdlib.h>
using namespace std;

class node
{
int data;
node *next,*prev;
public:
    node *create(node *);
    void insert(node *);
    void display(node *);
    void reverse(node *head);
    void del(node *);
};

node* node::create(node *head)
{
//head=new node;
head->prev=NULL;
head->next=NULL;
return head;
}

void node:: insert(node *head)
{
node *temp=new node;
cout<<"\nEnter data\n";
cin>>temp->data;
temp->prev=NULL;
temp->next=NULL;
node *curr;
curr=head->next;
if(head->next==NULL)
{
head->next=temp;
temp->prev=head;
}
else
{
while(curr->next!=NULL)
{
curr=curr->next;
}
curr->next=temp;
temp->prev=curr;
}
}

void node::display(node *head)
{
node *temp;
temp=head->next;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}

void node::reverse(node *head)
{
node *temp,*curr;
temp=head;
while(temp->next!=NULL)
temp=temp->next;


curr=temp;
while(curr!=head)
{
cout<<curr->data<<" ";
curr=curr->prev;
}    
}

void node::del(node *head)
{
node *temp,*curr;
temp=head;
cout<<"\nEnter val\n";
int val;
cin>>val;
while(temp->next->data!=val)
temp=temp->next;
curr=temp->next;
temp->next=curr->next;
curr->next->prev=curr->prev;
delete curr;
display(head);
}

int main()
{
node obj;
node *head=new node;
head=obj.create(head);
while(1)
{
cout<<"\n1:Insert"
    <<"\n2:Display"
    <<"\n3:Reverse"
    <<"\n4:Delete"
    <<"\n5:Exit";
cout<<"\nEnter choice\n";
int ch;
cin>>ch;
switch(ch)
{
case 1:
    cout<<"\nHow many node you want to insert\n";
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    obj.insert(head);
    break;
case 2:
    obj.display(head);
    break;
case 3:
    cout<<"\nReverse Display\n";
    obj.reverse(head);
    break;
case 4: obj.del(head);
    break;
case 5:
    exit(0);
}
}
}

/***************OUTPUT************************/

/*

compile: g++ filename.cpp

Execute: ./a.out

1:Insert
2:Display
3:Reverse
4: Delete
5: Exit
Enter choice
1

How many node you want to insert
5

Enter data
2

Enter data
3

Enter data

1

Enter data
6

Enter data
9

1:Insert
2:Display
3:Reverse
4: Delete
5: Exit
Enter choice
2
2 3 1 6 9
1:Insert
2:Display
3:Reverse
4: Delete
5: Exit
Enter choice
3

Reverse Display
9 6 1 3 2
1:Insert
2:Display
3:Reverse
4: Delete
5: Exit
Enter choice
4

Enter val
2
3 1 6 9
1:Insert
2:Display
3:Reverse
4: Delete
5: Exit
Enter choice5

 */

 

 

Post a Comment

0 Comments