@@ -29,7 +29,7 @@ You may assume that all operations are valid (for example, no pop or peek operat
2929
3030## 思路
3131
32- 这道题目是让我们用栈来模拟实现队列。 我们直到栈和队列都是一种受限的数据结构 。
32+ 这道题目是让我们用栈来模拟实现队列。 我们知道栈和队列都是一种受限的数据结构 。
3333栈的特点是只能在一端进行所有操作,队列的特点是只能在一端入队,另一端出队。
3434
3535在这里我们可以借助另外一个栈,也就是说用两个栈来实现队列的效果。这种做法的时间复杂度和空间复杂度都是O(n)。
@@ -64,7 +64,7 @@ push之前是这样的:
6464
6565## 代码
6666
67- * 语言支持:JS, Python
67+ * 语言支持:JS, Python, Java
6868
6969Javascript Code:
7070
@@ -183,6 +183,70 @@ class MyQueue:
183183# param_4 = obj.empty()
184184```
185185
186+ Java Code
187+
188+ ``` java
189+ class MyQueue {
190+ Stack<Integer > pushStack = new Stack<> ();
191+ Stack<Integer > popStack = new Stack<> ();
192+
193+ /* * Initialize your data structure here. */
194+ public MyQueue () {
195+
196+ }
197+
198+ /* * Push element x to the back of queue. */
199+ public void push (int x ) {
200+ while (! popStack. isEmpty()) {
201+ pushStack. push(popStack. pop());
202+ }
203+ pushStack. push(x);
204+ }
205+
206+ /* * Removes the element from in front of queue and returns that element. */
207+ public int pop () {
208+ while (! pushStack. isEmpty()) {
209+ popStack. push(pushStack. pop());
210+ }
211+ return popStack. pop();
212+ }
213+
214+ /* * Get the front element. */
215+ public int peek () {
216+ while (! pushStack. isEmpty()) {
217+ popStack. push(pushStack. pop());
218+ }
219+ return popStack. peek();
220+ }
221+
222+ /* * Returns whether the queue is empty. */
223+ public boolean empty () {
224+ return pushStack. isEmpty() && popStack. isEmpty();
225+ }
226+ }
227+
228+ /**
229+ * Your MyQueue object will be instantiated and called as such:
230+ * MyQueue obj = new MyQueue();
231+ * obj.push(x);
232+ * int param_2 = obj.pop();
233+ * int param_3 = obj.peek();
234+ * boolean param_4 = obj.empty();
235+ */
236+ ````
237+
186238## 扩展
187239 - 类似的题目有用队列实现栈,思路是完全一样的,大家有兴趣可以试一下。
188240 - 栈混洗也是借助另外一个栈来完成的,从这点来看,两者有相似之处。
241+
242+ ## 延伸阅读
243+
244+ 实际上现实中也有使用两个栈来实现队列的情况,那么为什么我们要用两个stack来实现一个queue?
245+
246+ 其实使用两个栈来替代一个队列的实现是为了在多进程中分开对同一个队列对读写操作。一个栈是用来读的,另一个是用来写的。当且仅当读栈满时或者写栈为空时,读写操作才会发生冲突。
247+
248+ 当只有一个线程对栈进行读写操作的时候,总有一个栈是空的。在多线程应用中,如果我们只有一个队列,为了线程安全,我们在读或者写队列的时候都需要锁住整个队列。而在两个栈的实现中,只要写入栈不为空,那么`push`操作的锁就不会影响到`pop`。
249+
250+ - [reference](https: // leetcode.com/problems/implement-queue-using-stacks/discuss/64284/Do-you-know-when-we-should-use-two-stacks-to-implement-a-queue)
251+
252+ - [further reading](https: // stackoverflow.com/questions/2050120/why-use-two-stacks-to-make-a-queue/2050402#2050402)
0 commit comments