算法-04-用两个栈实现队列

描述

用两个栈来实现一个队列,分别完成在队列尾部插入整数(push)和在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
 

示例

输入:
["PSH1","PSH2","POP","POP"]
返回值:
1,2

Java 实现

import java.util.Stack;
import java.lang.Exception;

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(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        if(stack2.isEmpty())
            return 0;
        return stack2.pop();
    }
}

Python 实现

# -*- 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:
            while(len(self.stack1)>0):
                self.stack2.append(self.stack1.pop())
                
        if len(self.stack2)==0:
            return 0;
        return self.stack2.pop()
不要小瞧女程序员
原文地址:https://www.cnblogs.com/shix0909/p/15032826.html