A stack is a linear data structure that follows Last In First Out (LIFO): the last element inserted is the first one removed.
Stack Operations
- Push — add an element to the top of the stack.
- Pop — remove an element from the top of the stack.
- IsEmpty — check if the stack is empty.
- IsFull — check if the stack is full.
- Peek — get the value of the top element without removing it.
Working of a Stack
- A pointer called
TOPtracks the top element of the stack. - When initializing the stack,
TOPis set to-1, soTOP == -1means empty. - On pushing,
TOPis incremented and the new element is placed at the position it points to. - On popping, the element at
TOPis returned andTOPis decremented. - Before pushing, check if the stack is already full.
- Before popping, check if the stack is already empty.
For the array-based implementation, push and pop both take constant time — O(1).