diff --git a/Stack/stack_implementation.cpp b/Stack/stack_implementation.cpp new file mode 100644 index 0000000..cba1dcc --- /dev/null +++ b/Stack/stack_implementation.cpp @@ -0,0 +1,80 @@ +#include +using namespace std; + +template // for generic node + +class node{ +public: + T data; + node* next; + node(T x){ // constructor + data = x; + next = NULL; + } +}; + +template // for generic stack +class Stack{ +public: + node* head; + + int count; + Stack(){ // constructor + head = NULL; + count = 0; + } + + void push(T x){ + count++; + node* n = new node(x); + if(head == NULL){ + head = n; + } + else{ + n->next = head; + head = n; + } + } + + void pop(){ + if(count>0){ + count--; + node* temp = head; + head = head->next; + delete temp; + + } + } + + int size(){ + return count; + } + + bool empty(){ + return head == NULL; // or count == 0 + } + + T top(){ //top element of stack + return head->data; + } + +}; + +int main() +{ + Stack s; + int n; // number of elements + cin >> n; + int element; + for(int i=1;i<=n;i++){ + cin >> element; + s.push(element); + } + + + while(!s.empty()){ // print all elements + cout << s.top()<<" "; + s.pop(); + } + return 0; +}