LIFO behavior
The newest element is always at the top. A Pop operation therefore removes the most recently pushed value.
A stack is a Last-In, First-Out (LIFO) data structure. Elements are inserted and removed only from the top. Think of a stack of plates: the last plate placed on top is the first one removed.
Enter a value and choose an operation.
push(value):
stack[top] = value
top = top + 1
The newest element is always at the top. A Pop operation therefore removes the most recently pushed value.
Overflow occurs when Push is attempted on a full fixed-capacity stack. Underflow occurs when Pop or Peek is attempted on an empty stack.
An array-based stack stores values in consecutive positions and maintains a top index. Push and Pop update only that index.
Stacks are used for function calls, undo operations, expression evaluation, syntax parsing, depth-first search, and backtracking.
| Operation | Time | Reason |
|---|---|---|
| Push | O(1) | The value is added directly at the top. |
| Pop | O(1) | Only the top value is removed. |
| Peek | O(1) | The top value is read without removal. |
| Search | O(n) | Every value may need to be checked from top to bottom. |
| Space | O(n) | Storage grows with the number of stack elements. |