【剑指offer】用两个栈实现队列 - Java实现

【剑指offer】用两个栈实现队列 - Java实现

题目描述

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

1. 分析

  1. 当插入时,直接插入 stack1
  2. 当弹出时,当 stack2 不为空,弹出 stack2 栈顶元素,如果 stack2 为空,将
    stack1 中的全部数逐个出栈入栈 stack2,再弹出 stack2 栈顶元素

2. 代码

Java实现

//java实现
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
        stack1.push(node);
    }
    public int pop() {
        if (stack2.size() <= 0) {
            while (stack1.size() != 0) {
            //当stack2为空,stack1不为空,stack1全部逐个出栈入栈stack2
                stack2.push(stack1.pop());
            }
        }
        //弹出stack2栈顶元素
        return stack2.pop();
    }
}

Python实现

//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()

你可能感兴趣的:(【剑指offer】用两个栈实现队列 - Java实现)