两个栈实现队列和两个队列实现栈-Python实现-复杂度分析

曾经终败给现在 2022-05-31 06:54 365阅读 0赞

###两个栈实现一个队列

入队:元素进栈A

出队:先判断栈B是否为空,为空则将栈A中的元素pop出来并push进栈B,再将栈B的第一个元素pop出栈,如不为空则直接从栈B中pop第一个元素出栈

分析:这样做入队的复杂度为O(1),出队的复杂度则变为O(n)。而直接用python的list实现队列,以list尾为队列首,则入队用insert,复杂度为O(n),出队用pop,复杂度为O(1)。

  1. class Queue:
  2. def __init__(self):
  3. self.stockA=[]
  4. self.stockB=[]
  5. def push(self, node):
  6. self.stockA.append(node)
  7. def pop(self):
  8. if self.stockA==[]:
  9. return None
  10. if self.stockB==[]:
  11. for i in range(len(self.stockA)):
  12. self.stockB.append(self.stockA.pop())
  13. return self.stockB.pop()

###两个队列实现一个栈

进栈:元素入队A

出栈:判断如果队A只有一个元素,则直接出队。否则,把队A中的元素出队并入队B,直到队A中只有一个元素,再直接出队。

分析:直接用python的list实现栈,以list尾为栈首,则出栈和进栈的复杂度都为O(1)。而用两个队列实现栈,因为进栈要用insert,因此复杂度为O(n);出栈复杂度为O(n^2),因为需要连续insert。

  1. class Stock:
  2. def __init__(self):
  3. self.queueA=[]
  4. self.queueB=[]
  5. def push(self, node):
  6. self.queueA.insert(0,node)
  7. def pop(self):
  8. if self.queueA==[]:
  9. return None
  10. while len(self.queueA)!=1:
  11. self.queueB.insert(0,self.queueA.pop())
  12. self.queueA,self.queueB=self.queueB,self.queueA
  13. return self.queueB.pop()

Life is short, You need Python~

发表评论

表情:
评论列表 (有 0 条评论,365人围观)

还没有评论,来说两句吧...

相关阅读