Saturday, February 7, 2015

Implementation of linked list and all operations in C++

#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;
node *next;
};
void display(node *s)
{
node *p;
p=s;
cout<<"\tThus the no's are as:\n";
while(p!=NULL)
{cout<<"\t"<<p->data<<endl;
p=p->next;
}
}
node *add_end(node *s,int d)
{
node *p,*l;
l=s;
while(l->next!=NULL)
l=l->next;
p=new(node);
p->data=d;
p->next=NULL;
l->next=p;
return s;
}
node *add_begin(node *s,int d)
{
node *p,*l;
p=s;
l=new(node);
l->data=d;
l->next=p;
s=l;
return s;
}
node *add_after(node *s,int d,int k)
{
node *p,*l;
p=s;
while(s->data!=d)
s=s->next;
l=new(node);
l->data=k;
l->next=s->next;
s->next=l;
return p;
}
node *add_before(node *s,int d,int k)
{
node *p,*l;
p=s;
if(p->data==d)
{
l=new(node);
    l->data=k;
    l->next=p;
   s=l;
    return s;
}
else
{
while(p->next->data!=d)
p=p->next;
l=new(node);
l->data=k;
l->next=p->next;
p->next=l;
return s;
}
}
node *del_end(node *s)
{
node *p;
p=s;
while(p->next->next!=NULL)
p=p->next;
p->next=NULL;
return s;
}
node *del_begin(node *s)
{
node *p;
p=s;
p=p->next;
s=p;
return s;
}
node *del_mid(node *s,int d)
{
node *p;
p=s;
while(p->next->data!=d)
p=p->next;
p->next=p->next->next;
return s;
}
int main()
{
node *s,*t,*l;
int d,k,n;
l=new(node);
s=l;
    cout<<"Start entering the no's.....Enter -1 for aborting...\n";
    cin>>d;
    l->data=d;
    l->next=NULL;
    cin>>d;
    while(d!=-1)
     {t=new(node);
      t->data=d;
      t->next=NULL;
      l->next=t;
      l=t;
      cin>>d;
     }
    display(s);
    while(1)
{
  cout<<"Select any of the options provided below....\n1:Adding at the end\n2:Adding at the beginning\n3:Adding after a specified no\n4:Adding before a specified no\n5:Deleting a no at the end\n6:Deleting a no at the beginning\n7:Deleting a no in between the no's\n8:For quitting\n";
  cin>>n;
       switch(n)
       {case 1 :cout<<"Enter the no:";
                cin>>d;
                s=add_end(s,d);
                display(s);
                break;
        case 2 :cout<<"Enter the no:";
                cin>>d;
                s=add_begin(s,d);
                display(s);
                break;
        case 3 :cout<<"Enter the no after which you want to enter:";
       cin>>d;
       cout<<"Enter the no:";
       cin>>k;
       s=add_after(s,d,k);
       display(s);
break;
case 4 :cout<<"Enter the no before which you want to enter:";
       cin>>d;
       cout<<"Enter the no:";
       cin>>k;
       s=add_before(s,d,k);
       display(s);
       break;
case 5 :s=del_end(s);
       display(s);
       break;
case 6 :s=del_begin(s);
       display(s);
       break;
case 7 :cout<<"Enter the no which you want to delete:";
       cin>>d;
       s=del_mid(s,d);
       display(s);
       break;
case 8 :cout<<"Thanks...";
       exit(1);
        default:cout<<"Wrong choice....Enter again\n";
                break;
       }
    }
}

No comments:

Post a Comment

Contributors

Translate