A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means the last element added to the stack is the first one to be removed.
Stack is one of the most used data structures due to its nature of Reverse ordering. Let me explain:
Function Call Stack Example
TOS is sometimes also referred as "head"
Adds an element on top of the stack.
++tos and not tos++?tos++, when doing the push operation first time, we
will be accidentally doing the following: which is NOT allowed and correct. so, in-order to avoid that, we first increase TOS by 1
and then assign the data at "newly increased" TOS index.Removes the top element from the stack.
Checks if the stack is full.
For limited size stack, if the TOS reaches the maximum index, it means the stack is full.
MAX - 1?MAX is the number of elements a stack can hold and here TOS is index which starts with 0, so to account that we need to subtract 1 from MAX.
Checks if the stack is empty.
Fundamentally, we know that if TOS is -1, it means the stack is empty.
Returns the top element of the stack.
Condition is that if the stack is empty, TOS will be -1. So if we try to access stack[-1], we will get error. In order to prevent that we are first checking if the stack is empty.