LeetCode-225 Implement Stack using Queues Solution (with Java)

1. Description:


Notes:

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-05-07
 3  * Your MyStack object will be instantiated and called as such:
 4  * MyStack obj = new MyStack();
 5  * obj.push(x);
 6  * int param_2 = obj.pop();
 7  * int param_3 = obj.top();
 8  * boolean param_4 = obj.empty();
 9  */
10 class MyStack {
11     /** Initialize your data structure here. */
12    private Queue<Integer> queue = new LinkedList<Integer>();
13 
14 
15     /** Push element x onto stack. */
16     public void push(int x) {
17         queue.add(x);
18         for(int i = 1; i < queue.size(); i++)
19             queue.add(queue.remove());
20     }
21 
22     /** Removes the element on top of the stack and returns that element. */
23     public int pop() {
24         return queue.remove();
25     }
26 
27     /** Get the top element. */
28     public int top() {
29         return queue.peek();
30     }
31 
32     /** Returns whether the stack is empty. */
33     public boolean empty() {
34         return queue.isEmpty();
35     }
36 }

猜你喜欢

转载自www.cnblogs.com/sheepcore/p/12395227.html