Sunday, October 14, 2012

Implementing Stack in C++ using Class Template


#include<iostream>
using namespace std;

template<class T>
class stack{
T* arr;
static int top;
public:
stack(int);
void push(T);
T pop();
bool empty();
};

template<class T>
int stack<T>::top = -1;

template<class T>
stack<T>::stack(int x){
this->arr = new T(x);
}

template<class T>
void stack<T>::push(T a){
this->arr[++top] = a;
}

template<class T>
T stack<T>::pop(){
T a = this->arr[top--];
return a;
}

template<class T>
bool stack<T>::empty(){
return (top==-1);
}

int main(){
stack<int> s(10);
int i;
for(i=0;i<10;i++){
s.push(i);
}
while(!s.empty()){
cout<<s.pop()<<endl;
}
return 0;
}

1 comment: