[Leetcode] 225. Implement Stack using Queues

Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

题目大意:使用队列(queue)实现栈(stack)。

实现方式很简单,每次push进新元素之后,将队列里保存的元素重新从队首弹出,然后从队尾入队。

 1 class MyStack {
 2 public:
 3     queue<int> q;
 4     /** Initialize your data structure here. */
 5     MyStack() {
 6         
 7     }
 8     
 9     /** Push element x onto stack. */
10     void push(int x) {
11         q.push(x);
12         for(int i=0;i<q.size()-1;i++)
13         {
14             q.push(q.front());
15             q.pop();
16         }
17             
18     }
19     
20     /** Removes the element on top of the stack and returns that element. */
21     int pop() {//注意,弹出时,需要返回弹出的元素值
22         int x = q.front();
23         q.pop();
24         return x;
25     }
26     
27     /** Get the top element. */
28     int top() {
29         return q.front();
30     }
31     
32     /** Returns whether the stack is empty. */
33     bool empty() {
34         return q.empty();
35     }
36 };
37 
38 /**
39  * Your MyStack object will be instantiated and called as such:
40  * MyStack obj = new MyStack();
41  * obj.push(x);
42  * int param_2 = obj.pop();
43  * int param_3 = obj.top();
44  * bool param_4 = obj.empty();
45  */
原文地址:https://www.cnblogs.com/hejunlin1992/p/7546131.html