A Deque
(double-ended queue) is a data structure that allows you to add and remove elements from both ends. In Java, the Deque
interface extends the Queue
interface and provides methods for inserting, removing, and examining elements at both the beginning and the end of the deque.
To use a Deque
as a stack in Java, you can follow these steps:
Deque
interface. Some common implementations of the Deque
interface in Java include ArrayDeque
and LinkedList
. You can choose the implementation based on your specific requirements (e.g. performance, capacity, thread-safety, etc.).Deque<Integer> stack = new ArrayDeque<>(); // Using an ArrayDeque
push
method to add elements to the top of the stack. The push
method inserts an element at the front of the deque.stack.push(1); // Stack: [1] stack.push(2); // Stack: [2, 1] stack.push(3); // Stack: [3, 2, 1]
pop
method to remove elements from the top of the stack. The pop
method removes and returns the first element of the deque.int x = stack.pop(); // x is 3, stack is [2, 1] int y = stack.pop(); // y is 2, stack is [1]
peek
method to examine the element at the top of the stack without removing it. The peek
method returns the first element of the deque, or null
if the deque is empty.int x = stack.peek(); // x is 1, stack is still [1]
isEmpty
method to check if the stack is empty. The isEmpty
method returns true
if the deque is empty, and false
otherwise.boolean x = stack.isEmpty(); // x is false stack.pop(); boolean y = stack.isEmpty(); // y is true
This is a basic example of how you can use a Deque
as a stack in Java. You can use the other methods of the Deque
interface to perform additional operations on the stack, such as inserting or removing elements from the end of the deque, or iterating over the elements of the deque.
Note that the Deque
interface provides several methods that have the same name and functionality as the methods of the Stack
class, but the Stack
class is now considered to be a legacy class and its use is discouraged. It is recommended to use a Deque
instead of a Stack
whenever possible.