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

1. 题目描述

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

2. 分析

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

如何用两个站实现队列,看下图两个栈:inout
图片链接https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3ea280b5-be7d-471b-ac76-ff020384357c.gif
图解: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()

猜你喜欢

转载自blog.csdn.net/weixin_44285445/article/details/108134618