剑指offer | 两个栈实现一个队列 | 06

思路分析

一个主栈,一个辅助栈.
push(x): 每次往主栈中进行加入即可
pop()/peek(): 将主栈最后一个元素之前的元素都先暂时放在辅助栈中,然后将主栈中的最后一个元素(就是队首元素)进行处理,最后再将辅助栈的元素还回去.
empty(): 就是判断主栈是否为空

cpp

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

    int pop() {
        while(stack1.size()){
            int t = stack1.top();
            stack1.pop();
            stack2.push(t);
        }
        int res = stack2.top();
        stack2.pop();
        while(stack2.size()){
            int t = stack2.top();
            stack2.pop();
            stack1.push(t);
        }
        
        return res;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

python

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.S1,self.S2=[],[]
    def push(self, node):
        self.S1.append(node)
    def pop(self):
        if not self.S1:return -1
        while self.S1:
            self.S2.append(self.S1.pop())
        res = self.S2.pop()
        while self.S2:
            self.S1.append(self.S2.pop())
        return res
原文地址:https://www.cnblogs.com/Rowry/p/14305303.html