Sai A Sai A
Updated date Jul 20, 2023
In this blog, we will explore various methods to convert a Deque (double-ended queue) to a Stack in Java.

Introduction:

In Java, a Deque is a versatile data structure that supports adding and removing elements from both ends. On the other hand, a Stack is a LIFO (Last-In-First-Out) data structure, commonly used in applications requiring strict ordering of elements. There are scenarios where you may need to convert a Deque into a Stack, either for compatibility reasons or to leverage Stack-specific operations. In this blog, we will discuss multiple strategies to achieve this conversion and explore their advantages and limitations.

Method 1: Using a Temporary Stack

One straightforward approach is to use a temporary Stack to perform the conversion. We can iterate over the Deque while pushing its elements onto the Stack. The elements will be reversed in the process, giving us a Stack-like behavior.

Deque<Integer> deque = new LinkedList<>();
deque.add(1);
deque.add(2);
deque.add(3);

Stack<Integer> stack = new Stack<>();
while (!deque.isEmpty()) {
    stack.push(deque.removeLast());
}

Output:

The Stack, after the conversion, will contain the elements in the reverse order they were originally in the Deque: [3, 2, 1].

By iterating over the Deque and using the removeLast() method, we extract elements from the Deque and push them onto the Stack using the push() method. The result is a Stack that contains the elements in the desired order.

Method 2: Extending the Stack Class

Another method involves creating a custom class that extends the Stack class and provides additional methods to convert a Deque to a Stack.

public class DequeToStack<E> extends Stack<E> {
    public DequeToStack(Deque<E> deque) {
        while (!deque.isEmpty()) {
            push(deque.removeLast());
        }
    }
}

Output:

The resulting DequeToStack object will contain the elements in the reverse order they were originally in the Deque.

By extending the Stack class, we inherit its functionality and can customize it to perform the conversion from Deque to Stack. The constructor of the custom class takes a Deque as a parameter and converts it by pushing its elements onto the Stack using the inherited push() method.

Conclusion:

In this blog, we explored multiple effective strategies to convert a Deque to a Stack in Java. We examined the temporary Stack approach, and extended the Stack class. Converting a Deque to a Stack allows you to leverage Stack-specific operations while preserving the original functionality of the Deque.

Comments (0)

There are no comments. Be the first to comment!!!