-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathimplementQueueUsingStack.java
More file actions
40 lines (35 loc) · 1.03 KB
/
Copy pathimplementQueueUsingStack.java
File metadata and controls
40 lines (35 loc) · 1.03 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
/* two stack: one for push, one for pop, o(n) */
public class MyQueue {
Stack<Integer> element = new Stack<>(); /* for push */
Stack<Integer> temp = new Stack<>(); /* for pop */
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
element.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
/* could write this part as a individual function */
if(temp.empty()){
while(!element.empty()){
temp.push(element.pop());
}
}
return temp.pop();
}
/** Get the front element. */
public int peek() {
if(temp.empty()){
while(!element.empty()){
temp.push(element.pop());
}
}
return temp.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return element.empty() && temp.empty();
}
}