Monday 21 September 2015

Linked list insertion and deletion at end

#include <iostream>
using namespace std;
struct node
   {
     int data ;
     node* next;
   };
node* head;
void insert(int x)
    {   node * temp=new node();
        temp->data=x;
    node*temp2=head;
          if(head==NULL)
             {
                 head =temp;
                 temp->next=NULL;
             }
  else
     {   while(temp2->next!=NULL)
        temp2=temp2->next;
        temp2->next=temp;
temp->next=NULL;
     }
}
void del()
{ node*temp2=head;
     if(head==NULL)
        cout<<"Linked is          empty"<<endl; 
    else
   
    while(temp2->next->next!=NULL)
       temp2=temp2->next;
     temp2->next=NULL;
   
    }
void show()
{ node*temp1=head;
while(temp1!=NULL)
{cout<<temp1->data<<"->";
       
       
    temp1=temp1->next;
    }
    cout<<"NULL"<<endl;
    }
int main()
{head=NULL;
char ch='y';int n;
    int x;
while(ch=='y'||ch=='Y')
    {
        cout<<"Enter 1 for insertion"<<endl;
        cout<<"Enter 2 for deletion"<<endl;
        cin>>n;
         switch (n)
        { case 1 : cout<<"Enter data:";
                   cin>>x;
                
           insert (x);
            break;
case 2 : del();
        break;
}
        cout<<"The linked list is:"<<endl;
        show();
        cout<<"Do you want to continue operation  y/n"<<endl;
    cin>>ch;
    }
}

No comments:

Post a Comment