232. Implement Queue using Stacks

这道题目是要求你使用stack简单地构建一个queue,实现和正常的queue的push,pop,front功能。
比较经典的一道题目了,也加深我们对栈和队列的理解。
描述:
Implement the following operations of a queue using stacks.

push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.

实现上述接口即可,并且题目中都给出了是int型的队列,所以不用用模板template了。

大致的思路如下:
1.入队列,仅仅将元素存储在arr1中即可。
2.查找的时候,因为要看最开始进入栈arr1的元素,也就是最底下的元素,这时候我们将所有元素倾倒到arr2中。
3.这时候的arr2支持队列的peek(front)和pop操作,因为无论你看还是删除,都是对arr2的top元素进行操作。并且注意一点:这里只有pop操作会影响其他操作,在arr2没被删空之前,只需要将之后push的元素存放在arr1中,arr2空了再一次执行倾倒操作。
这里写图片描述

class Queue {
public:
    stack<int> arr1;
    stack<int> arr2;
    // Push element x to the back of queue.
    void push(int x) {
        arr1.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if(arr2.empty()){
            while(!arr1.empty()){

                arr2.push(arr1.top());
                arr1.pop();
            }
        }
        arr2.pop();
    }

    // Get the front element.
    int peek(void) {
        if(arr2.empty()){
            while(!arr1.empty()){

                arr2.push(arr1.top());
                arr1.pop();
            }
        }
        return arr2.top();
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return arr1.empty()&&arr2.empty()?1:0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值