剑指offer笔记(九)栈和队列

栈:先进后出

队列:先进先出

  • 用栈实现队列

通过两个栈,利用先进后出的特性循环得到先进先出的特性

class MyQueue {
public:
    stack<int> pushst;
    stack<int> popst;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        pushst.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int top;
        if(!popst.empty())//出队栈非空
        {
            top=popst.top();
            popst.pop();
        }
        else//出队栈为空  入队栈填入出队栈
        {
            while(!pushst.empty())
            {
                popst.push(pushst.top());
                pushst.pop();
            }
            top=popst.top();
            popst.pop();
        }
        return top;
    }
    
    /** Get the front element. */
    int peek() {
        int top;
        if(popst.empty())//出队栈为空
        {
            while(!pushst.empty())
            {
                popst.push(pushst.top());
                pushst.pop();
            }
            top=popst.top();
        }
        else//出队栈非空
            top=popst.top();
        return top;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return pushst.empty()&&popst.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */
  •  用队列实现栈

 仅通过一个队列,循环进出实现栈“先进后出”

class MyStack {
public:
    queue<int> q;
    /** Initialize your data structure here. */
    MyStack() {

    }
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int n=q.size();
        while(n>1)//前n-1个先出队后入队
        {
            int front=q.front();
            q.pop();
            q.push(front);
            n--;
        }
        //n==1
        int top=q.front();
        q.pop();
        return top;
    }
    
    /** Get the top element. */
    int top() {
        return q.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HT . WANG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值