-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementQueueusingStacks_232.java
More file actions
47 lines (40 loc) · 1.3 KB
/
Copy pathImplementQueueusingStacks_232.java
File metadata and controls
47 lines (40 loc) · 1.3 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
43
44
45
46
47
package Stack_Queue;
import java.util.Stack;
public class ImplementQueueusingStacks_232 {
static class MyQueue {
Stack<Integer> op1,op2;
/** Initialize your data structure here. */
public MyQueue() {
op1=new Stack<>();
op2=new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
op1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(op2.isEmpty()&&op1.isEmpty()) throw new NullPointerException();
if(op2.isEmpty()){
while (!op1.isEmpty()){
op2.push(op1.pop());
}
}
return op2.pop();
}
/** Get the front element. */
public int peek() {
if(op2.isEmpty()&&op1.isEmpty()) throw new NullPointerException();
if(op2.isEmpty()){
while (!op1.isEmpty()){
op2.push(op1.pop());
}
}
return op2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return op2.isEmpty()&&op1.isEmpty();
}
}
}