1、两个队列实现一个栈
进栈:元素入队列A
出栈:判断如果队列A只有一个元素,则直接出队。否则,把队A中的元素出队并入队B,直到队A中只有一个元素,再直接出队。为了下一次继续操作,互换队A和队B。
python实现如下:
class StackWithTwoQueues(object):
#定义两个空队列
def __init__(self):
self.queue1 = []
self.queue2 = []
#入栈
def push(self, item):
self.queue1.append(item)
#出栈
def pop(self):
if len(self.queue1) == 0:
return(None)
while(len(self.queue1) != 1):
self.queue2.append(self.queue1.pop(0))
self.queue1, self.queue2 = self.queue2, self.queue1
return (self.queue2.pop())
#test
if __name__ == '__main__':
ss = StackWithTwoQueues()
list = [0, 1, 2, 3, 4]
for i in range(5):
ss.push(list[i])
print(list)
for i in range(5):
print(ss.pop(), ',', end = '')
#output
#[0, 1, 2, 3, 4]
#4, 3, 2, 1, 0
2、两个栈实现一个队列
入队:元素进栈A
出队:先判断栈B是否为空,为空则将栈A中的元素 pop 出来并 push 进栈B,再栈B出栈,如不为空则栈B直接出栈。
python实现如下:
class QueueWithTwoStacks(object):
#定义两个空栈
def __init__(self):
self.stack1 = []
self.stack2 = []
#入队
def enqueue(self, item):
self.stack1.append(item)
#出队
def dequeue(self):
if self.stack2:
return(self.stack2.pop())
else:
if self.stack1 != []:
while(self.stack1):
self.stack2.append(self.stack1.pop())
return(self.stack2.pop())
else:
return(None)
# test
if __name__ == '__main__':
qq = QueueWithTwoStacks()
list = [0, 1, 2, 3, 4]
for i in range(5):
qq.enqueue(list[i])
print(list)
for i in range(5):
print(qq.dequeue(), ',', end='')
#output
#[0, 1, 2, 3, 4]
#0, 1, 2, 3, 4,