LeetCode-232 Implement Queue using Stacks Solution (with Java)

Posted sheepcore

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-232 Implement Queue using Stacks Solution (with Java)相关的知识,希望对你有一定的参考价值。

1. Description:

Notes: 

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-03-07
 3  * Your MyQueue object will be instantiated and called as such:
 4  * MyQueue obj = new MyQueue();
 5  * obj.push(x);
 6  * int param_2 = obj.pop();
 7  * int param_3 = obj.peek();
 8  * boolean param_4 = obj.empty();
 9  */
10 class MyQueue {
11     /** Initialize your data structure here. */
12     Stack<Integer> input = new Stack<Integer>();
13     Stack<Integer> output = new Stack<Integer>();
14 
15     /** Push element x to the back of queue. */
16     public void push(int x) {
17         input.push(x);
18     }
19 
20     /** Removes the element from in front of queue and returns that element. */
21     public int pop() {
22         peek();
23         return output.pop();
24     }
25 
26     /** Get the front element. */
27     public int peek() {
28        if(output.empty()){
29            while (!input.empty()){
30                output.push(input.pop());
31            }
32        }
33        return output.peek();
34     }
35 
36     /** Returns whether the queue is empty. */
37     public boolean empty() {
38         return input.empty() && output.empty();
39     }
40 }

 

以上是关于LeetCode-232 Implement Queue using Stacks Solution (with Java)的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] 232. Implement Queue using Stacks

leetcode 232. Implement Queue using Stacks

LeetCode 232 Implement Queue using Stacks

LeetCode 232. Implement Queue using Stacks

leetcode- 232. Implement Queue using Stacks

[LeetCode] 232. Implement Queue using Stacks Java