Monday, 6 February 2012

Stack implementaion using link list in c++

In this post we have the representation of stack using a one-way linked list or singly linked list. The linked representation of a stack, commonly termed linked stack is a stack that is implemented using a singly linked list.
The INFO fields of the nodes hold the elements of the stack and the LINK fields hold pointers to the neighboring elements in the stack.
The start pointer of the linked list behaves as the top pointer variable of the stack and the null pointer of the last node in the list singles the bottom of the stack.

  
/******************************************************************************
Author: Sunil Kumar
Website: www.techdoon.com
Description: Stack implementaion using link list in c++
*******************************************************************************/

#include<iostream>
#include<cstdlib>
#include<memory>
using namespace std;
void menu();
class stack1
{
          public:
              int info;  //node data
              stack1 *link; // start node
              stack1(); //constructor for initialization
              void push();
              stack1* pop();
              stack1 getnode(); //memory allocation for new node 
      };
stack1 *top=NULL;
stack1::stack1()
{
                info=0;
                link=NULL;
                }
stack1* getnode()
{
       stack1 *tm;
       tm=new stack1;
       return tm;
       } 
void push(stack1* head)
{
     int item;
     cout<<"ITEM: "; cin>>item;
     head->info=item; //new node head's data initialiuzation
     head->link=top; //new node head's start initialize to top node 
     top=head; //top initialize to head address
 }
void pop()
{
     stack1 *tm;
     if(top!=0){
                       cout<<"\nPOP Element is "<<top->info;
                       tm=top;// getting top to tm to make it free
                       top=top->link; //top initialize to next
                       free(tm);
                       }
     else cout<<"\nStack UNDERFLOW.";
 }
int main()
{
    menu();
    return 0;
}
void menu()
{
     int ch;
     stack1 *temp;
     while(1){
     cout<<"\n1.PUSH.\n2.POP.\n0.EXIT."; cin>>ch;
     switch(ch)
     {
               case 1:temp=getnode(); 
                    if(temp!=NULL)push(temp);
                    else cout<<"Stack OVERFLOW.";
                    break;
               case 2:pop();
                      break;
               case 0: exit(0);
               default:
                       cout<<"INVALID";
                       break;
               }
               }
 }
  
    

Related Posts:



0 comments:

Post a Comment