Stack in Data Structure
Introduction
A stack is a linear data structure in which operations are done in a specific order. The order might be LIFO (Last In, First Out) or FILO (First In, Last Out).
Stack example
There are numerous real-world examples of stacks. Consider the canteen, where plates are heaped on top of one another. The plate at the top is the first to be removed, implying that the plate at the bottom is the one that remains in the stack for the longest duration. As a result, it can be observed to follow the LIFO (Last In, First Out)/FILO (First In, Last Out) order.
Applications of Stack in Real Life
- Bangles: Women wear their bangles one by one, and in order to remove the first one, they must first remove the last one.
- Books and Clothes: A excellent illustration of the stack is items piled on top of one another.
- Floors in a Building: If a person lives on the top floor and want to come out, he or she must first walk down to the first floor.
- Browsers: The stack is used by online browsers to keep track of the history of websites. If you click back, the previous site appears quickly.
- Mobile Phone: Mobile call logs use the stack; you must scroll to view a first person’s call log.
- Garage: if a garage's width is not sufficient. We need to remove all the vehicles that came after the initial one in order to remove it.
C++ stack implementation
- push: Adds a new element to the top of the stack, on top of the top element that is already there.
- pop: Removes the top element from the stack, which makes it one size smaller.
- isEmpty: Returns true If the stack is empty, which means that its size is 0. Or else, it returns false.
- isFull: Returns true if the stack is full, which means that its size has reached the limit of what can be stored on it. If the stack is not full, it returns false.
- peek: Returns the stack's top element without changing the stack.
- size: Returns the number of items in the stack.
Syntax
#include <iostream> |
Output:
Inserting 1 |
Time Complexity: O(1).