/*

The implementation of a simple Stack data structure in Arduino which uses LIFO (Last In/First Out)
principle where you peek at the top element in the stack, push a new one into the stack, or
pull the top element out.



*/


// Stack size
const int STACK_SIZE = 10;

class Stack {
  private:
    int stack[STACK_SIZE]; // Array to store stack elements
    int top;               // Index of the top element

  public:
    // Constructor to initialize the stack
    Stack() {
      top = -1; // Initialize top as -1 to indicate an empty stack
    }

    // Function to push an element onto the stack
    bool push(int value) {
      if (top >= STACK_SIZE - 1) {
        Serial.println("Stack overflow");
        return false; // Stack overflow
      }
      stack[++top] = value; // Increment top and push value
      Serial.print("Pushed: ");
      Serial.println(value);
      return true;
    }

    // Function to pop an element from the stack
    int pop() {
      if (top < 0) {
        Serial.println("Stack underflow");
        return -1; // Stack underflow
      }
      int value = stack[top--]; // Pop value and decrement top
      Serial.print("Popped: ");
      Serial.println(value);
      return value;
    }

    // Function to peek the top element of the stack
    int peek() {
      if (top < 0) {
        Serial.println("Stack is empty");
        return -1; // Empty stack
      }
      return stack[top];
    }

    // Function to check if the stack is empty
    bool isEmpty() {
      return top < 0;
    }

    // Function to check if the stack is full
    bool isFull() {
      return top >= STACK_SIZE - 1;
    }

    // Function to get the current size of the stack
    int size() {
      return top + 1;
    }
};

Stack stack; // Create a stack object

void setup() {
  Serial.begin(9600); // Initialize serial communication
  stack.push(10);     // Push values onto the stack
  stack.push(20);
  stack.push(30);
  stack.push(10);
  stack.push(22);

  int topValue = stack.peek(); // Peek at the top element
  Serial.print("Top element: ");
  Serial.println(topValue);

  stack.pop(); // Pop the top element

  while (!stack.isEmpty()) {
    stack.pop(); // Pop all elements
  }
}

void loop() {
  // Empty, all logic in setup
}