[5] Offer queue wins the python with two stacks implemented

Title Description

Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.

Ideas:

  • A stack is used as the queue
  • B queue for a stack, when the stack B is empty, stack A stack to stack all the B, B stack and then a stack (i.e., the queue)

Code:


# -*- 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 []
Published 99 original articles · won praise 6 · views 3998

Guess you like

Origin blog.csdn.net/weixin_42247922/article/details/103915908