Monday, 25 August 2014

Singly Linked List with recurrsion

#include "stdafx.h"
#include<iostream>
using namespace std;
struct node
{
int data;
node *next, *prev;
node()
{
next=NULL;
prev=NULL;
}
};
class DoublyLinkList
{
node *first;
public:
DoublyLinkList();
void insert(int s,int d);
void recInsert(node *temp,int s,int d);
void insertAt(int d,int index);
void display();
void remove();
void removeAt(int index);
void temporary();
void recDisplay(node *temp);

};
DoublyLinkList::DoublyLinkList()
{
first=NULL;
}
void DoublyLinkList::insert(int s,int d=0)
{

if(first==NULL)
{
cout<<"Enter data : ";
   cin>>d;
first=new node();
first->data=d;
first->next=NULL;
first->prev=NULL;
   s--;
node *ptr=first;
recInsert(ptr,s,d);
}
else
{
node *ptr=first;
recInsert(ptr,s,d);
}
}
void DoublyLinkList::recInsert(node *temp,int s,int d=0)
{
if(s>0){
cout<<"Enter data : ";
cin>>d;
temp->next=new node();
temp->next->data=d;
temp->next->next=NULL;
temp->next->prev=temp;
temp=temp->next;
s--;
recInsert(temp,s);
}
}
void DoublyLinkList::insertAt(int d,int index)
{
node *ptr=first;
if(first==NULL)
{
cout<<"\nLink not found!!!\n";

}
else
{
for(int i=1;i<index && ptr->next!=NULL;i++)
ptr=ptr->next;
}
node *temp=new node;
temp->data=d;
temp->next=ptr->next;
temp->next->prev=temp;
ptr->next=temp;
temp->prev=ptr;
}
void DoublyLinkList::remove()
{
if(first==NULL)
        {
           cout<<"\nNode not found"<<endl;
        }
         else
         {
           node *temp1=first;
  node *temp2=temp1;
             while(temp1->next!=NULL)
             {
                temp2=temp1;
                temp1=temp1->next;
             }
              delete temp1;
             temp2->next=NULL;
         }
}
void DoublyLinkList::removeAt(int index)
{
node *temp1=first;
int i=1;
while(i<index-1)
{
i++;
if(temp1==NULL)
{
    cout<<"\nLink not found!!!"<<endl;
}
else
{
temp1=temp1->next;
}
}
node *temp2=temp1->next;
temp1->next=temp1->next->next;
delete temp2;
}
void DoublyLinkList::display()
{
node *ptr=first;
if(first==NULL)
{
cout<<"\nList is Empty...!!!\n";
}
else
{
recDisplay(ptr);
}
}
void DoublyLinkList::recDisplay(node *temp)
{
if(temp==NULL)
{
cout<<endl;
}
else
{
cout<<temp->data;
temp=temp->next;
recDisplay(temp);
}
}
int main()
{
char ch;
int x,a;
DoublyLinkList s1;
cout<<"How many values you want to enter : ";
cin>>x;
s1.insert(x);
cout<<endl;
s1.display();
cout<<endl;
s1.remove();
cout<<endl;
s1.display();
cout<<endl;
cout<<"Enter the index no. to delete : ";
cin>>a;
s1.removeAt(a);
cout<<endl;
s1.display();
cout<<endl;
return 0;
}

No comments:

Post a Comment