Stack

Welcome to Stacks: Simplifying Computing.

What is Stack?

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.

Applications:

  • Function Call Management:When a function is called, the information about the function call is pushed onto the stack, and when the function completes, this information is popped off the stack.
  • Expression Evaluation:Stacks are often used to evaluate expressions, especially those involving parentheses. For example, in parsing mathematical expressions, you can use a stack to keep track of operators and operands.
  • Undo Mechanism:In applications like text editors, stacks are used to implement undo operations. Each edit operation is pushed onto the stack, and undo pops the operations off the stack.
  • Backtracking Algorithms:Stacks are employed in backtracking algorithms, where you need to explore different paths and return to previous choices.

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;
}

Reviews

Based on 0 reviews

No Comments Found

Developed By Aryan Thakur