A Templated Stack Data Structure Example

#include <stdio.h>
#include <iostream>

#define MAX_SIZE 1000 // MAXIMUM SIZE OF STACK

using std::endl;
using std::cout;
using std::cin;

template <typename Type>
class stack{
private:
int top; //index of topmost item pushed onto stack
Type array[MAX_SIZE]; // Contains all items
public:
stack(){//Constructor
top=-1; //Sets the Top Location to -1 indicating an empty stack
for(int i=0;i<MAX_SIZE;i++)
array[i]=NULL;//Initialises all stack items to NULL
}

void push(Type value){

if(top<MAX_SIZE-1){
top++;
array[top]=value;
}
else
{
cout<<“STACK IS FULL\n”;
}
}

Type pop() // Delete topmost item and return deleted item.
{
if(top>=0){
T value=array[top];
array[top]=NULL;
top–;
return value;
}
else
{
printf(“Stack is empty\n”);
return NULL;
}
}
};

int main()
{
// Example of using stack
stack <int> st;
int ch=0;
while (ch!=3)
{
cout<<“1) Push\n”;
cout<<“2) Pop\n”;
cout<<“3) Exit\n”;
cout<<“Enter your choise >> “;
cin>>ch;
switch(ch)
{
case 1:
int n;
cout<<“Push: “;
cin>>n;
st.push(n);
break;
case 2:
cout<<“Pop: “<<st.pop()<<“\n”;
break;
}
}
}

Filed under Programming.
0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments