Labels

Thursday 25 June 2015

SINGLY LINKLIST ALL OPERATIONS CODE

#include<iostream>
using namespace std;

class linkedlist
{
    public: struct node
    {
    int data;
    node *link;
    }*head;
        
           void append(int);
           void addafter(int,int);
           void search();
           void remove();    
           void display();
           linkedlist();    
};        
linkedlist::linkedlist()
    {
    head=NULL;
    }
void linkedlist::append(int item)
   {
    node *temp,*s;
    if(head==NULL)
    {
      temp=new node;
      temp->data=item;
      temp->link=NULL;
      head=temp;
    }
    else 
     {    
      temp=head;
      while(temp->link!=NULL)
      {
        temp=temp->link;
      }
        s=new node;
        s->data=item;
        s->link=NULL;
        temp->link=s;
      }
        
   }
void linkedlist::addafter(int loc,int item)
    {
    int i;
    node *temp,*s;

    temp=head;
    for(i=1;i<loc;i++)
    {
    temp=temp->link;
    }
        {
        if(temp==NULL)
        {
        cout<<"location is greater than linkedlist";
        }
        else
            {
            s=new node;
            s->data=item;
            s->link=temp->link;
            temp->link=s;
            }
        }
    }


void linkedlist::display()
    {
         node *temp;
     temp=head;
     while(temp!=NULL)
       {
         cout<<"["<<temp->data<<"]"<<"\n";
         temp=temp->link;  
           }
    }

void linkedlist::search()
{
    int i=0,key;
    node *temp;
    temp=new node;
    cout<<"Enter the element you wish to search";
    cin>>key;
    temp=head;
    while(temp->data != key)
        {
            if(temp==NULL)
            {
            cout<<"Element not found";
            }
            else
            {
            temp= temp->link;
            i++;
            }
        }
    cout<<"Your element is stored at"<<i<<"location";
}

void linkedlist::remove()
    {
        int key;
        node *temp,*p,*q,*r;
        temp=new node;
        cout<<"\n"<<"Enter the element you want to delete";
        cin>>key;
        while(temp->data !=key)
        {
            if(temp==NULL)
             {
             cout<<"Element not found";
             }
            else
                {
                temp= temp->link;
                }
        }
        p=temp;
        q=temp->link;
        r=q->link;
        p=r;
    }
    
int main()
{
linkedlist l;
l.append(15);
l.append(30);
l.append(44);
l.append(12);
l.addafter(2,41);
l.addafter(4,35);
l.search();
l.remove();
l.display();
return 0;
}