[5] to prove safety offer. Two stacks to queue [by Python]

Source

Title Description

Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.


  
  
  1. # -*- coding:utf-8 -*-
  2. '' '
  3. A is a push, B is out of the stack, when the stack, can go directly to A, while the stack, to determine whether there is an element,
  4. If no element B, pop is certainly an error, it should first of all A elements inside overwhelm B, an element and then pop the top, if B has direct pop out, you can,
  5. This is the best idea, two stacks achieved last out, together and achieve a FIFO queue.
  6. ' ''
  7. class Solution:
  8. # Initialize two stacks
  9. def __init__(self):
  10. self.stackA = []
  11. self.stackB = []
  12. # Achieved here only requires the push and pop operations queues are used respectively, and two press-pop stack represents
  13. def push(self, node):
  14. # write code here
  15. self.stackA.append(node)
  16. # Pop requires a priori conditions: If the queue is empty, None is returned
  17. def pop(self):
  18. # If there is an element of the stack is pushed directly pop
  19. if self. stackB:
  20. self.stackB.pop()
  21. A # If there are no elements Returns None
  22. elif Note self . stack:
  23. return None
  24. # If all elements A, B into the uniform press-pop performed
  25. else:
  26. while self. stackA:
  27. self.stackB.append( self.stackA.pop())
  28. return self.stackB.pop()

 

Guess you like

Origin blog.csdn.net/qq_33487726/article/details/91045871