1. The two stacks implement a queue
And two stacks stack1 stack2, when the push push directly into stack1, pop need to determine when and where stack1 in stack2. If it is not empty stack2, pop directly from stack2 if stack2 is empty, the value of the push stack1 stack2, and then the value of stack2 pop.
class Solution: def __init__(self): self.stack1 = [] self.stack2 = [] def push(self, node): # write code here self.stack1.append(node) def pop(self): # return xx if len(self.stack1) == 0 and len(self.stack2) == 0: return elif len(self.stack2) == 0: while len(self.stack1) > 0: self.stack2.append(self.stack1.pop()) return self.stack2.pop()
2. Stack two queues implemented a
Onto the stack: the queue elements A
Stack: A determination only if a queue element, directly dequeued. Otherwise, the team A team incorporated the elements of the team B, team A until only one element, and then directly from the team. In order to continue the next operation, exchange team A and team B.
class Stock: def __init__(self): self.queueA=[] self.queueB=[] def push(self, node): self.queueA.append(node) def pop(self): if len(self.queueA)==0: return None while len(self.queueA)!=1: self.queueB.append(self.queueA.pop(0)) self.queueA,self.queueB=self.queueB,self.queueA #交换是为了下一次的pop return self.queueB.pop()