How to Use Deque as a Stack in Java?
Last Updated :
29 Jan, 2024
The Deque extends the Queue interface and provides additional methods to support operation at both ends. This interface is part of the java.util package.
The Deque interface does not strictly enforce the order of elements, meaning that different implementations may behave differently. The standard implementations of Deque in Java include ArrayDeque and LinkedList. In this article, we will check How to use Deque as a Stack in Java.
Implement a Stack using Deque
In Java, you can use the Deque interface to implement a stack data structure. A Deque as “double-ended queue” and it provides methods to add and remove the elements from both ends. By using only, the methods from the end (push and pop), you can effectively use a Deque as a Stack.
Example:
Java
import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
class GFG {
public static void main (String[] args) {
Deque<Integer> stackDeque = new ArrayDeque<>();
stackDeque.push( 11 );
stackDeque.push( 12 );
stackDeque.push( 13 );
stackDeque.push( 14 );
System.out.println( "Deque Stack: " +stackDeque);
int peekElement = stackDeque.peek();
System.out.println( "Peeked Element: " +peekElement);
boolean isEmpty = stackDeque.isEmpty();
System.out.println( "Is stack is Empty? " +isEmpty);
int popElement = stackDeque.pop();
System.out.println( "Popped Element: " +popElement);
System.out.println( "Updated stack: " +stackDeque);
}
}
|
Output
Deque Stack: [14, 13, 12, 11]
Peeked Element: 14
Is stack is Empty? false
Popped Element: 14
Updated stack: [13, 12, 11]
Explanation of the above Program:
In this program, we can implement the basic operation of stack are push, pop, peek and isEmpty into the program.
- push() – To add elements to the top of the stack.
- pop() – method is used to remove the retrieve the elements from the top of the stack.
- peek() – It returns the top element of the stack.
- isEmpty() – return true if the elements in the stack otherwise false
Share your thoughts in the comments
Please Login to comment...