用栈结构来实现队列的入队和出队
思路:
1. A栈用来装入队的元素
2. B栈用来装出队的元素,如果B不为空,直接弹出即可实现出队,如果B为空,则把A中的元素弹出,压入到B栈
代码:
class Stack:
def __init__(self):
self.stack = []
self.top = -1
def is_empty(self):
return self.top == -1
def push(self, value):
self.stack.append(value)
self.top += 1
def pop(self):
if self.is_empty():
print("The stack is empty")
return None
value = self.stack.pop()
self.top -= 1
return value
def peek(self):
if self.is_empty():
return None
return self.stack[self.top]
class MyQueue:
def __init__(self):
self.A = Stack()
self.B = Stack()
def push(self, value):
self.A.push(value)
def pop(self):
if self.B.is_empty():
while not self.A.is_empty():
self.B.push(self.A.peek())
self.A.pop()
value = self.B.pop()
return value
def empty(self):
return self.A.is_empty() and self.B.is_empty()
q = MyQueue()
q.push(1)
q.push(2)
q.push(3)
q.push(4)
while not q.empty():
print(q.pop())
1
2
3
4
本文介绍了一种使用两个栈结构来实现队列数据结构的方法。主要思路是利用一个栈进行元素的入队操作,另一个栈用于出队操作。当出队栈为空时,将入队栈中的所有元素依次弹出并压入出队栈,从而实现了队列的先进先出特性。
508

被折叠的 条评论
为什么被折叠?



