题目:用两个栈实现队列
题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:有两个栈stackA,stackB,A为入栈,B为出栈的。入栈时,直接进入A即可,出栈时,先判断B中是否有元素,如果没有肯定不能pop(),应将A中所有元素倒压在B里面,再pop()最上面(后面)的元素,如果有,直接pop()就可以了。两个栈各自先进后出,在一起又实现了队列的新进先出。
# -*- 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 self.stackA:
self.stackB.append(self.stackA.pop())
return self.stackB.pop()
题目拓展:用两个队列实现一个栈
class Solution:
def __init__(self):
self.queueA=[]
self.queueB=[]
def push(self,node):
self.queueA.insert(0,node)
def pop(self):
if not self.queueA:
return None
while len(self.queueA)!=1:
self.queueB.insert(0,self.queueA.pop())
self.queueA,self.queueB=self.queueB,self.queueA #交换地址
return self.queueB.pop()
测试
#测试
if __name__=='__main__':
a=Solution()
a.push(1)
a.push(7)
a.push(3)
a.push(5)
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
print(a.pop())
在python中是直接操纵数据,数据处于主动地位,变量只是作为一种引用关系而存在,而不再拥有存储功能。
a=b
b=a
a,b=b,a#这两种操作得到的结果不一样