《剑指offer》5-使用2个栈实现队列【Java+Python】

使用2个栈实现队列

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

  2. 示例
    无 需要先明白2点:队列是先进先出的,栈是先进后出的

  3. 解题思路
    需要两个栈Stack1和Stack2,push的时候直接push进Stack1。pop需要判断Stack1和Stack2中元素的情况,Stack1空的话,直接从Stack2 pop,Stack1不空的话,把Stack1的元素push进入Stack2,然后pop Stack2的值。

1.push: 直接push进stack1。需要pop全部stack2,才开始将stack1元素放进stack2中

2.pop:if stack2 不为空,直接pop stack2;if stack2 为空,需要将stack1元素全部放入stack2中,然后pop

  1. 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.push(node);
        
    }
    
    public int pop() {
        if (stack1.isEmpty() && stack2.isEmpty()){
            return -1;
        }
        
        if (stack2.isEmpty()){
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    
    }
}
  1. 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 not self.stack1 and not self.stack2: 
            return 
        
        if not self.stack2: #如果stack2为空
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()   

如果您觉得本文有用,请点个“在看”
image.png

posted @ 2020-08-15 17:22  蜘蛛侠不会飞  阅读(109)  评论(0编辑  收藏  举报

俺的博客

https://blog.csdn.net/qq_40587575

俺的公众号