Sunday, 17 August 2014

TRAVERSAL AND INSERTION IN LINKED LIST

A simple LinkedList program that deletes and insert node at a particular location .



#include <iostream>       
using namespace std;

 struct node {
 node *next ;

     int data ;

    } ;

 struct node *head ;   
node* init(int a[] , int n)

 {
  node *head = NULL , *p ;

  for(int i=0;i<n;i++)

   {

    node *nd = new node() ;

    nd->data = a[i] ;

    if(i==0)

    {
    head = p = nd ;   

    }

    p->next = nd ;

    p = p->next ;

      

   }

   return head ;

    

 }

 void display (node *head)

 {

     node *p ;

     p = head ;

    while(p!=NULL)

     {

           cout<<p->data<<endl;

           p = p->next ;

        

     }

    

 }

 bool deleteMe(int x)

  {

   node *p = head ;

   if(head->data ==x)

    {

        head = head->next ;

    }

    else

    {

    while(p->next->data != x)

     {

        

         p = p->next ;

     }

     if(p->next->data == x)

      {

         

          p->next = p->next->next ;

          return 1 ;

      }

    }

          return 0 ;

  }

 void insertMe(int loc , int data)

  { 

      node *nd = new node();

      nd->data =  data ;

     node *p = head ;

     if(loc==1)

      {

          nd->next = head ;

          head = nd ;

         

      }else

      {

          for(int i=1 ; i<loc-1 ; i++)

           {

               p = p->next ;

              

           }

           nd->next = p->next ;

           p->next = nd ;

         

      }

     

  }

int main()

{

  int a[] = {1,2,3,4,5,6,7,8,9} ;

  head = init(a , 9) ;

  display(head) ;

  deleteMe(1) ; //delete the node with the given data

  cout<<endl<<endl ;

  display(head) ;

  cout<<endl<<endl ;

  insertMe(3 , 10);

  display(head) ;

  return 0;

}

No comments:

Post a Comment