A stack is a linear data structure that follows the LIFO(Last in First Out) principle. This basically means that the last item to be placed is the first one to be removed.
A good example is where you have a collection of voluminous books placed one on top of the other in a bag. You start out without any book and as you collect the books you like they pile up. The only way to access the first book you placed in the bag is by removing the last book on the top till you get to the first book. Removing a book from the stack is called pop while placing a book in the stack is known as push.
Common Operations on Stacks
Push: adding items in a stack, if a stack is full it is said to be in an overflow condition
Pop: removing items in a stack, if a stack is empty it is said to be in an underflow condition
isEmpty: checks if the stack is empty
isFull: checks if the stack is full
Peek: returns the topmost item on the stack without removing it
Applications of Stacks
Stacks can be used to:
-
Reverse a string due to the LIFO principle
-
Matching of parenthesis to check if they are equal closing and opening brackets
-
In web browsers to move forward or backward
-
Memory management in a computer, each program is allocated a memory location
-
Redo-undo in editors
Stacks can be implemented as arrays or as linked lists.