Skip to content

Instantly share code, notes, and snippets.

@ayushgp
Created January 27, 2016 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayushgp/10a1a8b0f71776faf245 to your computer and use it in GitHub Desktop.
Save ayushgp/10a1a8b0f71776faf245 to your computer and use it in GitHub Desktop.
#include<iostream>
using namespace std;
template<class T> struct Node{
T data;
Node<T>* next;
Node(T t){
this->data = t;
}
};
template<class T> class Stack{
private:
Node<T>* top;
public:
Stack();
T* getTop();
void push(T);
T* pop();
bool isEmpty();
};
template<class T> Stack<T>::Stack(){
top=NULL;
}
template<class T> T* Stack<T>::getTop(){
return top->data;
}
template<class T> void Stack<T>::push(T t){
Node<T>* newTop = new Node<T>(t);
newTop->next = top;
top = newTop;
}
template<class T> T* Stack<T>::pop(){
if(top==NULL) throw "Underflow!";
else {
T* popped = &top->data;
top = top->next;
return popped;
}
}
template<class T> bool Stack<T>::isEmpty(){
if(top!=NULL)return false;
return true;
}
int main(){
Stack<int> s;
s.push(2);
s.push(4);
s.push(4);
s.push(8);
s.push(9);
s.push(23);
s.push(1);
while(!s.isEmpty()){
cout<<*s.pop()<<endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment