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 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).


首先定义两个队列queue1、queue2

分析:用先进先出的队列实现后进先出的栈。

进栈:这里选取queue1进栈,直接queue.push(x)

出栈:即删除最后一个进入queue1的的元素,若queue1大小为1,则直接pop,若大于1,则把先进queue1的几个元素移入queue2中,至queue1只剩一个元素,然后删除钙元素,删除该元素后要记住:将queue2中的元素依次移入queue1

取栈顶元素:同出栈差不多,但有一点要注意:queue1只剩1个元素的时候,它就是栈顶元素,但同时,还是要把它移入queue2,然后在把queue2中的元素依次移入queue1,这么做是为了保证次序不变!!

AC代码如下:

class Stack {
public:
    queue<int>queue1;
    queue<int>queue2;
    // Push element x onto stack.
    void push(int x) 
    {
        queue1.push(x);
    }

    // Removes the element on top of the stack.
    void pop() 
    {
        if(queue1.size() == 1)
            queue1.pop();
        else
        {
            while(queue1.size() > 1)
            {
                int temp = queue1.front();
                queue1.pop();
                queue2.push(temp);
            }
            queue1.pop();
            //将队列2中的元素放回队列1,保证队列1中总有元素
            while(queue2.size() > 0)
            {
                int temp = queue2.front();
                queue2.pop();
                queue1.push(temp);
            }
        }
    }

    // Get the top element.
    int top() 
    {
        if(queue1.size() == 1)
            return queue1.front();
        else
        {
            while(queue1.size() > 1)
            {
                int temp = queue1.front();
                queue1.pop();
                queue2.push(temp);
            }
            int res = queue1.front();//找到栈定元素
            //找到栈定元素之后,一定要把栈定元素放到队列2中
            queue1.pop();
            queue2.push(res);
            //将队列2中的元素放回队列1,保证队列1中总有元素
            while(queue2.size() > 0)
            {
                int temp = queue2.front();
                queue2.pop();
                queue1.push(temp);
            }
            return res;
        }
    }

    // Return whether the stack is empty.
    bool empty() 
    {
        return queue1.empty() && queue2.empty();
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值