- A stack is a data structure that follows the Last In, First Out (LIFO) principle.
- It means that the last element added to the stack is the first one to be removed. Here’s a simple explanation with a diagram:
Stack Data Structure:
- A stack is like a collection of items stacked on top of each other. Think of it as a stack of books.
- You can only add or remove books from the top of the stack.
Operations:
- Push: Add an element to the top of the stack.
- Pop: Remove the element from the top of the stack.
- Peek (or Top): View the top element without removing it.
Diagram:
Let’s represent a stack with three elements (A, B, and C):

- Initially, the stack is empty.
- The element ‘A’ is pushed onto the stack.
- Then ‘B’ is pushed, and finally ‘C’ is pushed.
- The top of the stack is always the last element added (in this case, ‘C’).
- If we pop an element, ‘C’ will be removed first.
Operations:
-
Push ‘D’:

-
Pop:

- Peek (Top): (Without removing the top element) Simply displaying the top element
This diagram illustrates the basic idea of a stack. Elements are added to and removed from the top of the stack, and the top of the stack always represents the most recently added element.