Copyright © Programs ++
Design by Dzignine
Sunday, 20 May 2012

C++ implementation of linked list

// C++ implementation of a linked list

#include <iostream>

struct Node // declares the node structure
{
     int info;
     Node *next;
}*start,*ptr,*newptr;

Node *new_list(int x) // creates a new list
{
     ptr = new Node;
     ptr->info = x;
     ptr->next = NULL;
     return ptr;
}

void insert_beg(Node *np) // inserts an element in list
{
     if ( start == NULL )
          start = np;
     else
     {
          Node *save = new Node;
          save = start;
          start = np;
          np->next = save;
     }
}

void display(Node *np) // displays the list
{
     while ( np != NULL )
     {
          std::cout<<np->info<<" -> ";
          np = np->next;
     }
}

int main()
{
     int item,choice;
     do
     {
          std::cout<<" \n1 : Create a new list ";
          std::cout<<" \n2 : Insert at beginning ";
          std::cout<<" \n3 : Display List ";
          std::cout<<" \n4 : Exit\n ";
          std::cout<<"\n Enter your choide : ";
          std::cin>>choice;

          switch(choice)
          {
               case 1 :
                    std::cout<<" \nEnter some value : ";
                    std::cin>>item;
                    start = new_list(item);
                    std::cout<<" List created !!! ";
                    break;
               case 2 :
                    std::cout<<" Enter an item to insert : ";
                    std::cin>>item;
                    newptr = new Node;
                    newptr->info = item;
                    newptr->next = NULL;
                    insert_beg(newptr);
                    break;
               case 3 :
                    std::cout<<" The list is as follows : \n";
                    display(start);
                    break;
          } // end of switch

     }while ( choice != 4 ); // end of do while
     return 0;
}// end of main
------OUTPUT------

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.


1 comments:

  1. Thank you for such a simple code illustrating the creation and operating a linked list.

    ReplyDelete

Comment Here....