解题思路
首先队列是“先进先出”原则,栈是“先进后出”的原则
接下来设计两个栈,分为别positive和negative
当最初有元素要入队列的时候,我们让其进入positive栈中
如果需要出队列了,那么我们可以采取将positive中除了最底层的所有元素依次pop出来放进negative中
然后再将positive中剩下的一个元素弹出,即为最初入队列元素了
最后需要的时候再将negative中的元素依次放回positive中
实现代码:
class Stack:
def __init__(self):
self.memory = []
def push(self, element):
self.memory.append(element)
def pop(self):
return self.memory.pop() if (len(self.memory)!=0) else 'None'
def Stack_test():
a = Stack()
Stack.push(a, 1)
Stack.push(a, 2)
b = Stack()
Stack.push(b, 3)
print(Stack.pop(a))
Stack.push(a, 3)
print(a.memory)
class Queue:
def __init__(self):
self.positive = Stack()
self.negative = Stack()
def display(self):
if self.positive.memory:
print(self.positive.memory)
else:
while len(self.negative.memory) != 0:
pop_element = Stack.pop(self.negative)
Stack.push(self.positive,pop_element)
print(self.positive.memory)
def press(self,element):
if self.positive.memory:
Stack.push(self.positive,element)
else:
while len(self.negative.memory) != 0:
pop_element = Stack.pop(self.negative)
Stack.push(self.positive,pop_element)
Stack.push(self.positive, element)
def out(self):
if (len(self.positive.memory)==0) and (len(self.negative.memory) == 0):
return None
if len(self.positive.memory) == 1:
return Stack.pop(self.positive)
else:
while len(self.positive.memory)!=1:
pop_element = Stack.pop(self.positive)
Stack.push(self.negative,pop_element)
return Stack.pop(self.positive)
def Queue_test():
a = Queue()
Queue.press(a, 1)
Queue.press(a, 2)
a.display()
print(Queue.out(a))
a.display()
Queue.press(a, 2)
a.display()
if __name__ == '__main__':
# Stack_test()
Queue_test()
运行效果:
[1, 2]
1
[2]
[2, 2]