[leetcode] 225. Implement Stack using Queues 解题报告

来源:互联网 发布:鸟瞰图设计制作软件 编辑:程序博客网 时间:2024/05/29 10:56

题目链接:https://leetcode.com/problems/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).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.


思路:可以用一个队列模拟一个栈

1. 对于top,我们知道栈是先入后出,因此top会返回最后一个入栈的值,而这个值在队列的尾部。而我们不能得到尾部的值,所以可以将队列前面的值出队列并将出队列的值加入队列尾中,而最后一个就是我们要的值。

2. 对于pop,和top的思想是一样的,只是剩下最后一个值将不入队列。

3. 对于push,直接入队列即可。

4. 对于empty,如果队列都为空,则栈为空,否则不为空。

代码如下:

class Stack {public:    // Push element x onto stack.    void push(int x) {        que.push(x);    }    // Removes the element on top of the stack.    void pop() {        int k = que.size();        for(int i = 0; i< k-1; i++)        {            que.push(que.front());            que.pop();        }        que.pop();    }    // Get the top element.    int top() {        int k = que.size(), val;        for(int i = 0; i< k; i++)        {            if(i == k-1) val = que.front();            que.push(que.front());            que.pop();        }        return val;    }    // Return whether the stack is empty.    bool empty() {        return que.empty();    }private:    queue<int> que;};


0 0