用两个栈实现队列与用两个队列实现栈(Python实现)

用两个栈实现队列:

 1 class QueueWithTwoStacks(object):
 2     def __init__(self):
 3         self._stack1 = []
 4         self._stack2 = []
 5 
 6     def appendTail(self,x):
 7         self._stack1.append(x)
 8 
 9     def deleteHead(self):
10          if self._stack2:
11              return self._stack2.pop()
12          else:
13              if self._stack1:
14                 while self._stack1:
15                     self._stack2.append(self._stack1.pop())
16                 return self._stack2.pop()
17              else:
18                  return None

 

 

用两个队列实现栈:

 1 class StackWithTwoQueues(object):
 2     def __init__(self):
 3         self._stack1 = []
 4         self._stack2 = []
 5 
 6     def push(self,x):
 7         if len(self._stack1) == 0:
 8             self._stack1.append(x)
 9         elif len(self._stack2) == 0:
10             self._stack2.append(x)
11         if len(self._stack2) == 1 and len(self._stack1) >= 1:
12             while self._stack1:
13                 self._stack2.append(self._stack1.pop(0))
14         elif len(self._stack1) == 1 and len(self._stack2) > 1:
15             while self._stack2:
16                 self._stack1.append(self._stack2.pop(0))
17 
18     def pop(self):
19         if self._stack1:
20             return self._stack1.pop(0)
21         elif self._stack2:
22             return self._stack2.pop(0)
23         else:
24             return None

 

posted @ 2017-10-21 16:23  阿基米德的鸭子  阅读(4336)  评论(0编辑  收藏  举报