剑指offer笔记栈和队列

Posted AllenSquirrel

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指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();
 */

 

以上是关于剑指offer笔记栈和队列的主要内容,如果未能解决你的问题,请参考以下文章

剑指Offer数据结构之栈和队列[Python版]

剑指offer-包含min函数的栈-栈和队列-python

剑指offer-包含min函数的栈-栈和队列-python

剑指offer-用两个栈实现队列-栈和队列-python

剑指offer-面试题9-用两个栈实现队列-栈和队列

剑指offer:滑动窗口的最大值(栈和队列)