[leetcode] 225.Implement Stack using Queues

来源:互联网 发布:中国何时能拆掉网络墙 编辑:程序博客网 时间:2024/05/18 00:26

题目:
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).
题意:
使用两个队列实现一个栈。
思路:
使用队列que1,que2代表两个队列,由于队列的特点是先进先出FIFO。而栈的特点是先进后出LIFO。
入栈的操作就是简单的把数据加入队列。出栈的操作需要把该队列的数一个一个拿出来,最后的一个数是接下来应该出的数。假设que1中此刻含有n个数, 所以需要que2来装这次出来的n-1个数。最后的一个数就是出栈的数。所以就是连个队列来回装,每次的最后一个数就是栈顶的元素。
以上。
代码如下:

class Stack {public:    // Push element x onto stack.    void push(int x) {        if(empty() || !queue1.empty())            queue1.push(x);        else            queue2.push(x);    }    // Removes the element on top of the stack.    void pop() {        if(empty())return;        if(!queue1.empty())        {            while(!queue1.empty())            {                int tmp = queue1.front();                queue1.pop();                if(!queue1.empty())queue2.push(tmp);                            }        }        else        {            while(!queue2.empty())            {                int tmp = queue2.front();                queue2.pop();                if(!queue2.empty())queue1.push(tmp);                            }        }    }    // Get the top element.    int top() {        if(empty())return 0;        if(!queue1.empty())        {            int tmp = 0;            while(!queue1.empty())            {                tmp = queue1.front();                queue1.pop();                queue2.push(tmp);                            }            return tmp;        }        else        {            int tmp = 0;            while(!queue2.empty())            {                tmp = queue2.front();                queue2.pop();                queue1.push(tmp);                            }            return tmp;        }    }    // Return whether the stack is empty.    bool empty() {        return (queue1.empty() && queue2.empty());    }private:    queue<int> queue1;    queue<int> queue2;};
0 0
原创粉丝点击