leetcode之Implement Stack using Queues

来源:互联网 发布:局域网游戏排行榜知乎 编辑:程序博客网 时间:2024/06/15 19:58

题目:

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
解答:
就是直接用两个queue充当stack即可
class Stack {public:    // Push element x onto stack.    void push(int x) {        q1.push(x);    }    // Removes the element on top of the stack.    void pop() {        while(q1.size() != 1)        {            q2.push(q1.front());            q1.pop();        }        q1.pop();        while(!q2.empty())        {            q1.push(q2.front());            q2.pop();        }    }    // Get the top element.    int top() {        while(q1.size() != 1)        {            q2.push(q1.front());            q1.pop();        }        int t = q1.front();        q2.push(q1.front());        q1.pop();        while(!q2.empty())        {            q1.push(q2.front());            q2.pop();        }        return t;    }    // Return whether the stack is empty.    bool empty() {        return q1.empty();    }private:    queue<int> q1;    queue<int> q2;};

0 0
原创粉丝点击