-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-232-Implement-Queue-using-Stacks.java
101 lines (82 loc) · 2.25 KB
/
LeetCode-232-Implement-Queue-using-Stacks.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// class MyQueue {
// Stack<Integer> head;
// Stack<Integer> tail;
// public MyQueue(){
// head = new Stack<Integer>();
// tail = new Stack<Integer>();
// }
// // 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 int pop() {
// if(empty()) return -1;
// if(head.isEmpty()){
// transfer(head, tail);
// }
// return head.pop();
// }
// // Get the front element.
// public int peek() {
// if(empty()) return -1;
// if(head.isEmpty()){
// transfer(head, tail);
// }
// return head.peek();
// }
// // Return whether the queue is empty.
// public boolean empty() {
// // if(head.isEmpty() && tail.isEmpty()) return true;
// // return false;
// return head.isEmpty() && tail.isEmpty();
// }
// private void transfer(Stack head, Stack tail){
// while(!tail.isEmpty()){
// head.push(tail.pop());
// }
// }
// }
/*
Queue: FIFO
Stack: LIFO
*/
class MyQueue {
Stack<Integer> enqueue;
Stack<Integer> dequeue;
/** Initialize your data structure here. */
public MyQueue() {
enqueue = new Stack<>();
dequeue = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
enqueue.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return dequeue.pop();
}
/** Get the front element. */
public int peek() {
if (dequeue.isEmpty()) {
while (!enqueue.isEmpty()) {
dequeue.push(enqueue.pop());
}
}
return dequeue.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return dequeue.isEmpty() && enqueue.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/