Created
January 27, 2016 10:43
-
-
Save ayushgp/10a1a8b0f71776faf245 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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