【剑指Offer】 5.用两个栈实现队列 python实现

题目描述

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

思路:

  • 栈A用来作入队列
  • 栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列)

代码:


# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stackA = []
        self.stackB = []

    def push(self, node):
        # write code here
        self.stackA.append(node)

    def pop(self):
        # return xx
        if self.stackB:
            return self.stackB.pop()

        elif not self.stackA:
            return None
        else:

            # while 循环
            while self.stackA:
                #
                self.stackB.append(self.stackA.pop())  # 默认弹出列表的最后一个元素
            # print("===",self.stackB)  # [4, 3, 2, 1]
            return self.stackB.pop()

    def getQueue(self):
        print("stackA", self.stackA)
        print("stackB", self.stackB)


# 我大Python的内建数据结构太强大,可以用list直接实现栈,简单快捷。
sta = Solution()
sta.push(1)
sta.getQueue()
sta.push(2)
sta.getQueue()
sta.push(3)
sta.getQueue()
sta.push(4)
sta.getQueue()  # stackA [1, 2, 3, 4] stackB []

print(sta.pop())  # 1
sta.getQueue()  # stackA [] stackB [4, 3, 2]
print(sta.pop())  # 2
sta.getQueue()  # stackA [] stackB [4, 3]
print(sta.pop())  # 3
sta.getQueue()  # stackA [] stackB [4]
print(sta.pop())  # 4
sta.getQueue()  # stackA [] stackB []
发布了99 篇原创文章 · 获赞 6 · 访问量 3998

猜你喜欢

转载自blog.csdn.net/weixin_42247922/article/details/103915908