Data Structure
LABORATORY
Lab. Sheet Three
Link Stack
Computer engineering department
Second class
Linear Stack:
#include "stdafx.h"
#include<iostream>
using namespace std ;
#define N 10
template<class T >
class ArrayStack
{
private:
T a[N];
int top ; // stack top
public:
ArrayStack() //constructor
{top= -1 ; }
void push( T item ) // add an item on top of stack
{
if( top== N-1 )
{cout<<"Stack is Full " << endl;
return ;
}
top++ ; //increament top
a[top] = item ;
}
T pop() //remove an item from top of stack
{
if(isEmpty())
{
cout<<"Stack is empty " <<endl ;
return NULL ;
}
T item= a[top] ; //access top item
top-- ; //decrement top
return item ;
T peek()
{
if (isEmpty() ) return NULL ;
return a[top] ;
}
bool isEmpty()
{
return (top== -1) ;}
int size()
{return top+1 ; }
};
void main()
{ int i,n ;
ArrayStack<char> cs ;
[Link] ('A') ; [Link]('B');
[Link] ('C') ; [Link]('D');
[Link] ('E') ; [Link]('F');
n= [Link]() ;
cout<<"\nPoped items from char stack : " ;
for(i= 0 ;i<n ; i++)
cout<<" " << [Link]() ;
ArrayStack<int> ints ;
[Link](11);
[Link] (22);
[Link] (33);
[Link](44);
n=[Link]( ) ;
cout<<"\nPopped items from integer stack : " ;
for(i=0 ; i<n ; i++)
cout<< " " <<[Link]() ;
ArrayStack<char*> ss ;
[Link]("Alpha");
[Link] ("Beta");
[Link] ("Gamma");
n= [Link]() ;
cout<<"\nPoped items from char stack : " ;
for(i= 0 ;i<n ; i++)
cout<<" " << [Link]() ;
cout<<"\n\n";
}
Lab Exercise:
Because an array size is fixed, in the array (linear) representation of a stack, only a
fixed number of elements can be pushed onto the stack. If in a program the number of
elements to be pushed exceeds the size of the array, the program may terminate in an
error. We can overcome these problems by emplementing Stack using link list.
Exercises:
1. Write function copyStack makes an identical copy of a stack. The function
should use push and pop functions.
2. Using stack datastructuer conseept ,write a program to implement Postfix
Expressions Calculator.
Note:- In your program you should enter inphix mathamtical
expression , and that would be evaluated as Postfix