美文网首页
剑指offer之两个用两个栈实现队列功能

剑指offer之两个用两个栈实现队列功能

作者: 继续向前冲 | 来源:发表于2018-08-22 17:31 被阅读19次

题目一:用两个栈实现队列功能
题目二:用过两个队列实现一个栈的功能

解析:由于栈是先进后出,所以push的时候想用stack 入栈,当要pop的时候 因为要取的实际上是栈的最后一个,所以把stack1 的数据都push到stack2里,最后为实际数据,实际pop的是stack2的数据, 当有新数据push的时候,可以继续放到stack1中,不用每次都push到stack2中,只有当stack2为空时,进行一次转换即可。

队列转栈部分稍微复杂,push的时候还是存到queue1中,当需要pop时,把queue1的数据push到queue2中,直到queue1中剩一个数据,这个数据即为返回结果,为了方便理解,然后把queue2的数据在push到queue1中,这样每次pop的时候都要进行一次颠倒,既可以实现该功能。

#include <iostream>
#include "stack"
#include "queue"
using namespace std;
//题目一
class Solution {
private:
    stack<int> stack1;
    stack<int> stack2;
    
public:
    void push(int node) {
        stack1.push(node);
    }
    int pop() {
        if (stack2.empty()) {
            while (!stack1.empty()) {
                int val = stack1.top();
                stack1.pop();
                stack2.push(val);
            }
        }
        
        int val = stack2.top();
        stack2.pop();
        
        return val;
    }
};
//题目二
class queueClass {
private:
    queue<int> queue1;
    queue<int> queue2;
public:
    void push(int node) {
        queue1.push(node);
    }
    int pop() {
        int i = queue1.size();
        for (int n=0; n<i-1; n++) {
            queue2.push(queue1.front());
            queue1.pop();
        }
        
        int val = queue1.front();
        queue1.pop();
        
        while (!queue2.empty()) {
            queue1.push(queue2.front());
            queue2.pop();
        }
        
        return val;
    }
};

int main(int argc, const char * argv[]) {

    queueClass * a = new queueClass();
    a->push(1);
    a->push(2);
    a->push(3);
    a->push(4);
    a->push(5);
    a->push(6);
    
    
    std::cout << a->pop()<<endl;
    std::cout << a->pop()<<endl;
    std::cout << a->pop()<<endl;
    return 0;
}

相关文章

网友评论

      本文标题:剑指offer之两个用两个栈实现队列功能

      本文链接:https://www.haomeiwen.com/subject/ybyyiftx.html