diff --git a/C/stack push & pop opeartion b/C/stack push & pop opeartion new file mode 100644 index 0000000..a93da0a --- /dev/null +++ b/C/stack push & pop opeartion @@ -0,0 +1,77 @@ +#include +#include +using namespace std; +#define SIZE 10 +template +class stack +{ +X *arr; +int top; +int capacity; +public: +stack(int size = SIZE); void push(X); +X pop(); +X peek(); +int size(); +bool isEmpty(); bool isFull(); +~stack(){ +delete[] arr; } + +}; +template stack::stack(int size) +{ +arr = new X[size]; +capacity = size; +top = -1; } +template +void stack::push(X x) +{ +if (isFull()) { +cout << "OverFlow\nProgram Terminated\n"; +exit(EXIT_FAILURE); } +cout << "Inserting " << x << endl; +arr[++top] = x; } +template +X stack::pop() +{ +if (isEmpty()) +{ +cout << "UnderFlow\nProgram Terminated\n"; +exit(EXIT_FAILURE); } +cout << "Removing " << peek() << endl; +return arr[top--]; +} +template +X stack::peek() +{ +if (!isEmpty()) +return arr[top]; +else +exit(EXIT_FAILURE); +} +template +int stack::size() +{ +return top + 1; } +template +bool stack::isEmpty() { +return top == -1; // or return size() == 0; +} +template +bool stack::isFull() +{ +return top == capacity - 1; +} +int main() { +stack pt(2); pt.push("A"); pt.push("B"); pt.pop(); +// or return size() == capacity; +pt.pop(); +pt.push("C"); +cout << "Top element is: " << pt.peek() << endl; + +if (pt.isEmpty()) +cout << "Stack Is Empty\n"; +else +cout << "Stack Is Not Empty\n"; +return 0; } +