Stack Data Structure is a linear data structure that follows LIFO (Last In First Out) Principle , so the last element inserted is the first to be popped out. In this article, we will cover all the basics of Stack, Operations on Stack, its implementation, advantages, disadvantages which will help you solve all the problems based on Stack.
Table of Content
Stack is a linear data structure based on LIFO(Last In First Out) principle in which the insertion of a new element and removal of an existing element takes place at the same end represented as the top of the stack.
To implement the stack, it is required to maintain the pointer to the top of the stack , which is the last element to be inserted because we can access the elements only on the top of the stack.
This strategy states that the element that is inserted last will come out first. You can take a pile of plates kept on top of each other as a real-life example. The plate which we put last is on the top and since we remove the plate that is at the top, we can say that the plate that was put last comes out first.
Stack follows LIFO (Last In First Out) Principle so the element which is pushed last is popped first.
In order to make manipulations in a stack, there are certain operations provided to us.
Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.
Algorithm for Push Operation:
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:
Returns the top element of the stack.
Algorithm for Top Operation:
Returns true if the stack is empty, else false.
Algorithm for isEmpty Operation :
Returns true if the stack is full, else false.
Algorithm for isFull Operation:
The basic operations that can be performed on a stack include push, pop, and peek. There are two ways to implement a stack –
In an array-based implementation, the push operation is implemented by incrementing the index of the top element and storing the new element at that index. The pop operation is implemented by returning the value stored at the top index and then decrementing the index of the top element.
In a linked list-based implementation, the push operation is implemented by creating a new node with the new element and setting the next pointer of the current top node to the new node. The pop operation is implemented by setting the next pointer of the current top node to the next node and returning the value of the current top node.
Java