《剑指offer》面试题9:用两个栈实现一个队列

题目描述

知识点:栈,队列

思路:
两个栈Stack_A,Stack_B

push:
无论什么情况都压入A

pop:
当B中有元素时:直接栈顶出栈;
当B为空栈时:将A中元素逐个出栈压入B,B栈顶再出栈

代码:

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.Stack_A = []
        self.Stack_B = []
        
    def push(self, node):
        # write code here
        self.Stack_A.append(node)
        
    def pop(self):
        # return xx
        if not self.Stack_B:    # B空
            while self.Stack_A:
                self.Stack_B.append(self.Stack_A.pop())    # A全部出栈压入B
        return self.Stack_B.pop()
        

扩展:用两个队列实现栈

思路:
push: 压入不为空的队列
pop: 不为空的队列前n-1个元素出队进入另一个队列,最后一个元素出队

代码:

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

    def push(self, node):
        if not self.Queue_A: # QA为空,压入QB
            self.Queue_B.append(node)
        else:
            self.Queue_A.append(node)

    def pop(self):
        if not self.Queue_A and not self.Queue_B:
            return
            
        if not self.Queue_A: # QA为空
            n = len(self.Queue_B)
            self.Queue_A.extend(self.Queue_B[:n-1])
            self.Queue_B = self.Queue_B[-1:]
            return self.Queue_B.pop()

        if not self.Queue_B: # QA为空
            n = len(self.Queue_A)
            self.Queue_B.extend(self.Queue_A[:n-1])
            self.Queue_A = self.Queue_A[-1:]
            return self.Queue_A.pop()

s = Solution()
s.push(1)
s.push(2)
s.push(3)
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值