LeetCode 之 Implement Queue using Stacks — C++ 实现

Implement Queue using Stacks

 

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.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
利用栈实现队列的如下操作:

  • push(x) -- 将元素放入队尾。
  • pop() -- 移除队列头的元素。
  • peek() -- 返回队列头元素。
  • empty() -- 返回队列是否为空。
说明:

  • 只能使用栈的标准操作--即push to top, peek/pop from top, size,和 is empty 合法。
  • 使用的语言不一定有栈结构,但可以使用链表或队列模拟栈,只要使用栈的标准操作就可以。
  • 假设所有操作都合法(例如,当队列空时不会执行 pop 和 peek 操作)。


分析:

    因为栈是 FILO 结构,队列是 LIFO 结构,入队操作和压栈操作一样,但是出栈操作和出队操作相反,可以使用辅助栈,出队时将数据压入辅助栈,返回栈底(队头)元素后再将元素存回原来的栈。

class Queue {
public:
    // Push element x to the back of queue.
    void push(int x) {
        squeue.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
       stack<int> temp;
       stackSwap(squeue, temp);
       temp.pop();
       stackSwap(temp, squeue);
       
       return;
    }

    // Get the front element.
    int peek(void) {
        int ret = 0;
        stack<int> temp;
        stackSwap(squeue, temp);
        ret = temp.top();
        stackSwap(temp, squeue);
        
        return ret;
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return squeue.empty();
    }
    
    void stackSwap(stack<int> &src, stack<int> &dst)
    {
        int srcSize = src.size();
        for(int i = 0; i < srcSize; ++i)
        {
           dst.push(src.top());
           src.pop();
        }
        
        return;
    }
    
private:
    stack<int> squeue;
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值