Stack
Welcome to Stacks: Simplifying Computing.
Welcome to Stacks: Simplifying Computing.
A stack is a fundamental data structure in computer science that operates on the Last In, First Out (LIFO) principle. It is a collection of elements with two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element. Think of it as a stack of plates; you add a plate to the top (push), and you take the topmost plate off (pop). Stacks are commonly used for managing function calls, handling expressions in programming, and efficiently managing memory in computer systems.
Empty?
top -1
#include <iostream> using namespace std; class MyStack { private: int size; int top = -1; int *stack = nullptr; public: MyStack(int size) { this->size = size; stack = new int[size]; if (stack == nullptr) cout << "Memory Allocation Failed"; } void MyStack_push(int value) { if (top >= size - 1) { cerr << "*** Memory Allocation Failed for value: " << value << endl; return; } stack[++top] = value; return; } int MyStack_pop() { if (top == -1) { cout << "Nothing to pop"; return -1; } return stack[top--]; } int MyStack_top() { if (top == -1) { cout << "Stack Empty"; return -1; } return stack[top]; } bool MyStack_isEmpty() { return (top == -1 ? 1 : 0); } ~MyStack() { delete[] stack; } }; int main() { MyStack st(10); st.MyStack_push(10); st.MyStack_push(20); st.MyStack_push(30); st.MyStack_push(40); st.MyStack_push(50); st.MyStack_push(60); st.MyStack_push(70); st.MyStack_push(80); st.MyStack_push(90); st.MyStack_push(100); st.MyStack_push(110); return 0; }
No Comments Found