Use Deque as stack

Use Deque as stack

Easy Java Collections 28 views
Explanation Complexity

Problem Statement

Task: implement a small stack using Deque and support push/pop/peek.

Input Format

No direct user input.
Operations supported:

• push(x)

• pop()

• peek()

Output Format

Values returned by pop() and peek() operations.

Example

push(10)
push(20)
peek()
pop()
peek()
20
20
10

Constraints

• Use Deque

• Stack follows LIFO (Last In First Out)

• Do not use Stack class

Concept Explanation

A stack works on Last In First Out.
Deque can act like a stack because it allows operations at one end.

Step-by-Step Explanation

1.Create a Deque using ArrayDeque.

2.push(x)

• Add element at the front using addFirst(x).

2.pop()

• Remove and return the front element using removeFirst().

3.peek()

• Return the front element without removing using peekFirst().

4.All operations happen from the same end, so LIFO order is maintained

Concept Explanation

A stack works on Last In First Out.
Deque can act like a stack because it allows operations at one end.

Step-by-Step Explanation

1.Create a Deque using ArrayDeque.

2.push(x)

• Add element at the front using addFirst(x).

2.pop()

• Remove and return the front element using removeFirst().

3.peek()

• Return the front element without removing using peekFirst().

4.All operations happen from the same end, so LIFO order is maintained

Input / Output Format

Input Format
No direct user input.
Operations supported:

• push(x)

• pop()

• peek()
Output Format
Values returned by pop() and peek() operations.
Constraints
• Use Deque

• Stack follows LIFO (Last In First Out)

• Do not use Stack class

Examples

Input:
push(10) push(20) peek() pop() peek()
Output:
20 20 10

Example Solution (Public)

Java
static java.util.Deque<Integer> newStack(){return new java.util.ArrayDeque<>();}

Official Solution Code

static java.util.Deque<Integer> newStack(){return new java.util.ArrayDeque<>();}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.