知识点:栈,队列
思路:
两个栈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())