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.


2 comments:

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

    ReplyDelete
  2. Casino Tycoon - New York, NY - Mapyro
    Casino 태백 출장샵 Tycoon, New York, 화성 출장마사지 NY. Phone: 남양주 출장마사지 1-888-226-4700 진주 출장마사지 Website: https://www.apollo.io/CasinoRooms/Rooms/Casinos/Casino/Casino/View 여주 출장마사지 Profile. More information

    ReplyDelete

Comment Here....