A stack is a linear data structure that operates on the Last-In-First-Out (LIFO) principle. The Stacks has only one end, but the Queue has two (front and rear). It just has one pointer (top pointer) that points to the stack’s topmost element. When a new element is added to the stack, it is placed at the top, and the element can only be removed from the stack. To put it another way, a stack may be thought of as a container in which insertion and deletion can be done from the top of the stack.
In a linear data structure format, a stack represents a sequence of objects or elements. All operations are performed on the top position of the stack, which has a bounded bottom. The top value is incremented by one whenever an element is added to the stack by the push operation, and it is decremented by one whenever an element is pulled out of the stack by the pop operation. The stack pointer is a pointer that points to the top of the stack.
Operation of Stacks
The following are some operations –
The following are the steps involved in the PUSH operation:
- We verify whether a stack is full before adding an element to it.
- The overflow problem happens when we try to insert the element into a stack that is already full.
- We set the value of top to -1 when we create a stack to ensure that it is empty.
- When a new element is pushed into a stack, the value of the top is first incremented, i.e. top=top+1, and then the element is moved to the new top position.
- The items will be placed till the stack reaches its maximum size.
The following are the steps involved in the POP operation:
- We check whether the stack is empty before deleting the element from it.
- When we try to remove an element from an empty stack, we get an underflow condition.
- If the stack isn’t empty, we start with the element pointed to by the top.
- The top is decremented by one after the pop operation, i.e. top=top-1.
Fig 1 – Push n pop Operation Example
Interested in learning about similar topics? Here are a few hand-picked blogs for you!