All About C++

Get Pure Concepts of C++

Wednesday, 10 February 2016

how To delete data from singly link list in data structure with the example of source code

To delete a node from start, end or mid from singly link list

Below is a source code to delete data from single link list

void delnode()           //deleting
{  node *temp1,*temp2,*temp3;
   
    char d;

    cout<<"press 's' to delete from start,'m' for midd , 'e' for end"<<endl;
    cin>>d;
    switch (d)
    {
      case's':               //delete startif(start==NULL)
          { if(head==NULL)
              cout<<"no node to delete"<<endl;
          }
          else
          {
              temp1=start;
              start=start->next;
              delete temp1;
          }
         break;
      case'e':            //delete endif(start==NULL)
          { if(start==NULL)

              cout<<"no node to delete"<<endl;
          }
         else
         {
             temp1=start;
             while(temp1->next!=NULL)
             {
                temp2=temp1;
                temp1=temp1->next;
             }
              delete temp1;
             temp2->next=NULL;
         }
        break;
      case'm':               //delete midint num;
          cout<<"enter node you want to delete"<<endl;
          cin>>num;
         
          temp1=start;
          for(int i=1;i<num;i++)
          {
              if(start==NULL)
               cout<<"given node does not exist"<<endl;
              else
              {
                temp2=temp1;
                temp1=temp1->next;
              }
          }
          temp3=temp1->next;
          temp2->next=temp3;
          delete temp1;
          break;
    }

}