Stack
Stack
A stack is a basic data structure in computer science that adheres to the Last-In-First-Out (LIFO)
rule.
It is comparable to a stack of books where the last book added is the first one to be taken out.
A stack is a collection of components that can be accessed using the push and pop operations.
While the pop operation takes the top element out of the stack, the push operation adds an
element to the top of the stack.
The topmost element can also be examined without deleting it due to the peek procedure.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are five
memory blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is empty.
We have taken the stack of size 5 as shown below in which we are pushing the elements
one by one until the stack becomes full.
When we perform the delete operation on the stack, there is only one way for entry and
exit as the other end is closed.
It follows the LIFO pattern, which means that the value entered first will be removed last.
In the above case, the value 5 is entered first, so it will be removed only after the deletion
of all the other elements.
PUSH operation
The steps involved in the PUSH operation is given below:
o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition
occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-
1.
o Balancing of symbols: Stack is used for balancing a symbol. For example, we have
the following program: As we know, each program has an
opening and closing braces; when the opening braces come, we push the braces in
a stack, and when the closing braces appear, we pop the opening braces from the
stack. Therefore, the net value comes out to be zero. If any symbol is left in the
stack, it means that some syntax occurs in a program.
o Memory management: The stack manages the memory. The memory is assigned
in the contiguous memory blocks. The memory is known as stack memory as all
the variables are assigned in a function call stack memory.. When the function is
created, all its variables are assigned in the stack memory. When the function
completed its execution, all the variables assigned in the stack are released.