225. Implement Stack using Queues

Posted __Meng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 backpeek/pop from frontsize, 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).

 

用队列实现栈的功能

 

C++(2ms):

 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             q.push(q.front()) ;
14             q.pop() ;
15         }
16     }
17     
18     /** Removes the element on top of the stack and returns that element. */
19     int pop() {
20         int t = q.front() ;
21         q.pop() ;
22         return t ;
23     }
24     
25     /** Get the top element. */
26     int top() {
27         return q.front() ;
28     }
29     
30     /** Returns whether the stack is empty. */
31     bool empty() {
32         return q.empty() ;
33     }
34 };
35 
36 /**
37  * Your MyStack object will be instantiated and called as such:
38  * MyStack obj = new MyStack();
39  * obj.push(x);
40  * int param_2 = obj.pop();
41  * int param_3 = obj.top();
42  * bool param_4 = obj.empty();
43  */

 

以上是关于225. Implement Stack using Queues的主要内容,如果未能解决你的问题,请参考以下文章

225. Implement Stack using Queues

225. Implement Stack using Queues

225. Implement Stack using Queues

225. Implement Stack using Queues

[leetcode]225. Implement Stack using Queues

225. Implement Stack using Queues