Stack
Stack
the last element inserted is the first to be popped out. It means both insertion and
deletion operations happen at one end only.
Types of Stack:
Fixed Size Stack : As the name suggests, a fixed size stack has a fixed size
and cannot grow or shrink dynamically. If the stack is full and an attempt is
made to add an element to it, an overflow error occurs. If the stack is empty
and an attempt is made to remove an element from it, an underflow error
occurs.
Dynamic Size Stack : A dynamic size stack can grow or shrink dynamically.
When the stack is full, it automatically increases its size to accommodate the
new element, and when the stack is empty, it decreases its size. This type of
stack is implemented using a linked list, as it allows for easy resizing of the
stack.
Implementation of Stack in Data Structures
You can perform the implementation of stacks in data structures using two data
structures that are an array and a linked list.
Array: In array implementation, the stack is formed using an array. All the
operations are performed using arrays. You will see how all operations can
be implemented on the stack in data structures using an array data structure.
Linked-List: Every new element is inserted as a top element in the linked list
implementation of stacks in data structures. That means every newly inserted
element is pointed to the top. Whenever you want to remove an element
from the stack, remove the node indicated by the top, by moving the top to
its previous node in the list.
Basic Operations on Stack:
In order to make manipulations in a stack, there are certain operations provided to
us.
push() to insert an element into the stack
pop() to remove an element from the stack
top() Returns the top element of the stack.
isEmpty() returns true if stack is empty else false.
isFull() returns true if the stack is full else false.
Push Operation on Stack
Adds an item to the stack. If the stack is full, then it is said to be an Overflow
condition.
Algorithm for Push Operation:
Before pushing the element to the stack, we check if the stack is full .
If the stack is full (top == capacity-1) , then Stack Overflows and we
cannot insert the element to the stack.
Otherwise, we increment the value of top by 1 (top = top + 1) and the new
value is inserted at top position .
The elements can be pushed into the stack till we reach the capacity of the
stack.
Pop Operation in Stack
Removes an item from the stack. The items are popped in the reversed order in
which they are pushed. If the stack is empty, then it is said to be an Underflow
condition.
Algorithm for Pop Operation:
Before popping the element from the stack, we check if the stack is empty .
If the stack is empty (top == -1), then Stack Underflows and we cannot
remove any element from the stack.
Otherwise, we store the value at top, decrement the value of top by 1 (top =
top - 1) and return the stored top value.
top()
O(1) O(1)
or peek()