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 Program to Implement a // Stack using Deque import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
// Driver Class class GFG {
// main function
public static void main (String[] args) {
// Create the Deque
Deque<Integer> stackDeque = new ArrayDeque<>();
// Push the element into stackDeque
stackDeque.push( 11 );
stackDeque.push( 12 );
stackDeque.push( 13 );
stackDeque.push( 14 );
// Print the stackDeque
System.out.println( "Deque Stack: " +stackDeque);
// Print the peek element in the stack
int peekElement = stackDeque.peek();
System.out.println( "Peeked Element: " +peekElement);
// Check the stack is empty or not
boolean isEmpty = stackDeque.isEmpty();
System.out.println( "Is stack is Empty? " +isEmpty);
// Pop the element into the stack
int popElement = stackDeque.pop();
System.out.println( "Popped Element: " +popElement);
// Print the updated stack
System.out.println( "Updated stack: " +stackDeque);
}
} |
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