Title Description
Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.
Ideas:
Violence: two stacks stack1, stack2. stack1 used to store data, the data at each push, by stack2 divided by 2., the data in stack1 taken out, and then to push data into them. Finally, then put back the original data.
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
for i in range(len(self.stack1)):
self.stack2.append(self.stack1.pop())
self.stack1.append(node)
for i in range(len(self.stack2)):
self.stack1.append(self.stack2.pop())
def pop(self):
return self.stack1.pop()
# return xx
optimization:
stack1 used as a stack, stack2 with make stack. As long as there is data in stack2, can directly; stack2 if there is no data, and the data sequentially in stack1 stack2 attached to the inside.
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if len(self.stack2)<0:
for i in range(len(self.stack1)):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()