Amazon Affiliate

Thursday 31 May 2012

INSERT A NODE INTO A SIMPLE LINKED LIST AT THE END OF THE LIST...

// INSERT A NODE INTO A SIMPLE LINKED LIST AT THE END OF THE LIST


 # include <iostream.h>
 # include <alloc.h>
 # include<conio.h>

  struct link
    {
      char info[20];
      struct link *next;
    };

     class insert
     {
    private:
        int i;
        int number;
        link start, *previous, *new1;

    public:
         void insertion(link *);
         void create_list(link *);
         void display(link *);

      };

// Function create a linked list

  void insert :: create_list( link *node)
     {

   start.next = NULL;  // Empty list

   node = &start;      // Point to the start of the list
   i = 0;
   cout<<"\n Input choice n for break: ";
   char ch = getche();
   while(ch != 'n')
     {
       node->next = (struct link* ) malloc(sizeof(struct link));
       node = node->next;
       cout<<"\n Input the node :"<<(i+1)<<" : ";
       cin>>node->info;
       node->next = NULL;
       cout<<"\n Input choice n for break: ";
       ch = getche();
       i++;
     }
   }

// Inserting a node
    void insert :: insertion(link *node)
    {
     node = start.next;
     previous = &start;


     while(node)
      {
          node = node->next;
          previous= previous->next;
      }
         if(node == NULL)
           {
         new1 = (struct link* ) malloc(sizeof(struct link));
         new1->next = node ;
         previous->next = new1;
         cout<<"\n Input the last node value: ";
         cin>>new1->info;
           }
      }

// Display the list

  void insert :: display(link *node)
    {
    node = start.next;
    cout<<"\n After Inserting a node list is as follows:\n";
    while (node)
      { cout<<"\n "<<node;
    cout<<"  "<< node->info;
    node = node->next;
      }
    }
     void main()
     {
        insert i_mode;
        link *node = (link *) malloc(sizeof(link));

        i_mode.create_list(node);
        i_mode.insertion(node);
        i_mode.display(node);
     }

No comments:

Post a Comment