C++ Linked List Program

Program:


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

class node;

node *START;  // Points to first element in the list
int N;  // Tracks No. of nodes

class node
{
public:
 node *next; // pointer to next node
 int value; // data item

 node()
      {
 next=NULL;
 value=0;
      }

      void show();
      void insertItem();
      void deleteItem();

};

void node::show()
{
 if(START==NULL)
      { cout<<"\nList Empty!";
      }
       else
     {
 cout<<"\nElements in the list are: \n";
 node *ptr;
 ptr=START;
 while(ptr!=NULL)
      {
    cout<<ptr->value<<endl;
    ptr=ptr->next;
      }
     }
}

void node::insertItem()
{
 int pos, item;
 cout<<"\nEnter position, 0(at beginning) to "<<N<<"-(at the end): ";
 cin>>pos;
 cout<<"\nEnter Item value: ";
 cin>>item;
 node *newNode = new node();
 newNode->value=item;

 if(pos==0)
      {
 newNode->next=START;
 START=newNode;
       }
       else
      {
       int Cpos=1; // current position
       node *ptr = START;
  while(Cpos!=pos)
 {
  ptr=ptr->next;
  Cpos++;
 }

 newNode->next=ptr->next;
 ptr->next=newNode;
      }

      cout<<"\nInserted!";
       N++; // increment number of items
}

void node::deleteItem()
{
   if(START==NULL)
  {
     cout<<"\nList Empty!";
  }
   else
  {
     int pos, item;
     cout<<"\nEnter position 1 to "<<N<<": ";
     cin>>pos;

     if(pos==1)
   {
     item=START->value;  // save deleted value;
     START = START->next;
   }
     else
   {
     node *ptr, *prev;
     int Cpos=1; // current pos
     ptr=START;
     while(Cpos!=pos)
    {
     prev=ptr;          // prev points to node preceeding ptr
     ptr=ptr->next;
     Cpos++;
    }
     item=ptr->value;
     prev->next=ptr->next;
   }
     cout<<"\nItem Deleted: "<<item;
     N--; // decrement number of nodes

  }
}

void main()
{
 int choice;
 do
 {
 clrscr();
 cout<<"\n1. Insert Node\n";
 cout<<"2. Delete Node\n";
 cout<<"3. View List\n";
 cout<<"4. Exit\n";
 cout<<"\nEnter Choice: ";
 cin>>choice;
 switch(choice)
      {
 case 1: START->insertItem();
 break;
 case 2:START->deleteItem();
 break;
 case 3: START->show();
 break;
 case 4: return;
      }
  getch();
 }while(choice!=4);
}
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...
 
Posts RSSComments RSSBack to top
© 2013 Updated Tech News Results and Reviews