剑指offer第五题两个栈实现队列功能

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

【题目分析】:这个题目其实算是一道简单题,只要有数据结构理论的,完全可以理解整个过程,其核心思想就是两个栈,一个用来push原始进入,类似仓库的功能,仓库的元素按照栈的规则存放入货架,再从货架pop元素就可以了,这个题有一个知识盲点,就是为什么每次执行完就要将元素pop一下,其实就是保证当前循环的正常进行和当前执行原始是新元素。

class Solution
{
public:
    void push(int node) {
        storage.push(node);
    }


    int pop() {
        int ret;//定义需要pop的元素;
        if(shelf.empty()){
            while(!storage.empty()){
                ret=storage.top();
                shelf.push(ret);
                storage.pop();
            }
        }
        ret=shelf.top();
        shelf.pop();
        return ret;
        
    }


private:
    stack<int> storage;
    stack<int> shelf;
};

LeetCode232leetcode

使用栈来实现队列的如下操作:

  • push(x) -- 将一个元素放入队列的尾部。
  • pop() -- 从队列首部移除元素。
  • peek() -- 返回队列首部的元素。
  • empty() -- 返回队列是否为空。

注意:

  • 你只能使用标准的栈操作-- 也就是只有push to toppeek/pop from topsize, 和 is empty 操作是可使用的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque (双端队列)来模拟一个栈,只要你仅使用栈的标准操作就可以。
  • 假设所有操作都是有效的,比如 pop 或者 peek 操作不会作用于一个空队列上。
class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {}
    
    /** Push element x to the back of queue. */
    void push(int x) {
        sta.push(x);
    }
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int res;
        if(shelf.empty()){
            while(!sta.empty()){
                res=sta.top();
                shelf.push(res);
                sta.pop();
            }
        }
        res=shelf.top();
        shelf.pop();
        return res;
            
    }
    
    /** Get the front element. */
    int peek() {
        if (shelf.empty()){  
        while(!sta.empty())  
        {  
            int res = sta.top();    
            shelf.push(res);
            sta.pop();}    
        }  
        if (!shelf.empty())  
        {  
            return shelf.top();  
        }  
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return sta.empty()&&shelf.empty();
    }

private:
    stack<int> sta;
    stack<int> shelf;
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值