LeetCode-232 (자바) 스택 솔루션을 사용하여 큐를 구현

1. 설명 :

노트: 

2. 예 :

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 }

 

추천

출처www.cnblogs.com/sheepcore/p/12395208.html