Title Description
Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.
-
# -*- coding:utf-8 -*-
-
''
'
-
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,
-
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,
-
This is the best idea, two stacks achieved last out, together and achieve a FIFO queue.
-
'
''
-
class Solution:
-
# Initialize two stacks
-
def __init__(self):
-
self.stackA = []
-
self.stackB = []
-
# Achieved here only requires the push and pop operations queues are used respectively, and two press-pop stack represents
-
def push(self, node):
-
# write code here
-
self.stackA.append(node)
-
# Pop requires a priori conditions: If the queue is empty, None is returned
-
def pop(self):
-
# If there is an element of the stack is pushed directly pop
-
if
self.
stackB:
-
self.stackB.pop()
-
A # If there are no elements Returns None
-
elif
Note
self
.
stack:
-
return None
-
# If all elements A, B into the uniform press-pop performed
-
else:
-
while
self.
stackA:
-
self.stackB.append(
self.stackA.pop())
-
return
self.stackB.pop()