From 33c90c49042776acf3b97c5bc34035d6a18184f8 Mon Sep 17 00:00:00 2001 From: Rudrakshi Date: Sun, 11 Oct 2020 00:51:21 +0530 Subject: [PATCH] Added stack --- Stack/stack_implementation.cpp | 80 ++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 Stack/stack_implementation.cpp 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; +}