用两个栈实现队列详解(附Java、Python源码)——《剑指Offer》

时间:2022-07-25
本文章向大家介绍用两个栈实现队列详解(附Java、Python源码)——《剑指Offer》,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

2. 分析

队列是:“先进先出” 栈是:“先进后出

如何用两个站实现队列,看下图两个栈:inout

图解:push 操作就直接往in中 push, pop 操作需要分类一下:如果out栈为空,那么需要将in栈中的数据转移到out栈中,然后在对out栈进行 pop,如果out栈不为空,直接 pop 就可以了。

3. 代码实现

3.1 Java实现

import java.util.Stack;

public class JzOffer5 {
    Stack<Integer> in = new Stack<Integer>();
    Stack<Integer> out = new Stack<Integer>();

    public void push(int node){
        in.push(node);
    }

    public int pop(){
        if (out.isEmpty()) {
            while (!in.isEmpty()) {
                out.push(in.pop());
            }
        }
        return out.pop();
    }
}

3.2 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())
        return self.stack2.pop()