-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueUsingStack.java
More file actions
executable file
·42 lines (32 loc) · 1.02 KB
/
Copy pathQueueUsingStack.java
File metadata and controls
executable file
·42 lines (32 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.codeWithArsalon.LinearDS;
import java.util.Stack;
public class QueueUsingStack {
private Stack<Integer> stackOne = new Stack<>();
private Stack<Integer> stackTwo = new Stack<>();
//O(1) operation
public void enqueue(int item) {
stackOne.push(item);
}
//O(n) operation
public int dequeue() {
if (isEmpty()) //more meaningful exception
throw new IllegalStateException();
moveStackOneToStackTwo(); //refactored
return stackTwo.pop();
}
public int peek() {
if (isEmpty()) //more meaningful exception
throw new IllegalStateException();
moveStackOneToStackTwo(); //refactored
return stackTwo.peek();
}
private void moveStackOneToStackTwo() {
if (stackTwo.isEmpty()) {
while (!stackOne.isEmpty())
stackTwo.push(stackOne.pop()); //reversing stack order
}
}
public boolean isEmpty () {
return stackOne.isEmpty() && stackTwo.isEmpty();
}
}