剑指05两个栈实现一个队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
        
        
    }

    int pop() {
        int a;
        if (stack2.empty()){
            while (!stack1.empty())
            {
                a=stack1.top();
                stack2.push(a);
                stack1.pop();
            }        }
        a=stack2.top();
        stack2.pop();
        return a;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
 
 
import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        if (stack1.empty()&& stack2.empty()){
            throw new RuntimeException("Queue is empty!");
        }
        if (stack2.empty())
        {
            while (!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }    
        return stack2.pop();
    }
}
 
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1=[]
        self.stack2=[]
    def push(self, node):
        # write code here
        self.stack1.append(node)
    def pop(self):
        # return xx
        if len(self.stack2)>0:
            return self.stack2.pop()
        while self.stack1:
            self.stack2.append(self.stack1.pop())
        if len(self.stack2)>0:
            return self.stack2.pop()
原文地址:https://www.cnblogs.com/hrnn/p/13358671.html