-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementQueueUsingStacks.java
More file actions
executable file
·52 lines (46 loc) · 1.14 KB
/
ImplementQueueUsingStacks.java
File metadata and controls
executable file
·52 lines (46 loc) · 1.14 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
48
49
50
51
52
package code.coder.lee.easy;
import java.util.Stack;
/**
* Created by bcc on 16/3/28.
*/
public class ImplementQueueUsingStacks {
public Stack<Integer> head;
public Stack<Integer> tail;
}
class MyQueue{
private Stack<Integer> head = new Stack<>();
private Stack<Integer> tail = new Stack<>();
// Push element x to the back of queue.
public void push(int x) {
tail.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if (!head.empty()){
head.pop();
}else if (!tail.empty()){
while (!tail.empty()){
head.push(tail.pop());
}
head.pop();
}
}
// Get the front element.
public int peek() {
if (head.empty()&&tail.empty()){
return -1;
}
if (!head.empty()){
return head.peek();
}else{
while (!tail.empty()){
head.push(tail.pop());
}
return head.peek();
}
}
// Return whether the queue is empty.
public boolean empty() {
return head.empty()&&tail.empty();
}
}