-
两个栈实现队列
-
方法
stack_in 、 stack_out
一个栈用于push,一个栈用于pop
-
push:
stack_in [1 2 3 4]
stack_out []
-
pop
stack_in []
stack_out [1 2 3]
-
-
原理
一个序列先进栈,再出栈,此时可以操纵队头元素
例如: 1 2 3 4 5 6
进栈:-> 1 2 3 4 5 6
-
实现
class MyQueue: """ 两个栈实现队列 """ def __init__(self): """ Initialize your data structure here. """ self._stack_in = [] self._stack_out = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ self._stack_in.append(x) if not self._stack_out: while self._stack_in: self._stack_out.append(self._stack_in.pop()) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if self._stack_out: return self._stack_out.pop() elif self._stack_in: while self._stack_in: self._stack_out.append(self._stack_in.pop()) return self._stack_out.pop() else: return None def peek(self) -> int: """ Get the front element. """ if self._stack_out: return self._stack_out[-1] elif self._stack_in: while self._stack_in: self._stack_out.append(self._stack_in.pop()) return self._stack_out[-1] else: return None def empty(self) -> bool: """ Returns whether the queue is empty. """ return len(self._stack_out) == 0 and len(self._stack_in) == 0
-
-
两个队列实现栈
-
方法
-
pop
队列 1 2 3 4 5
出栈也就是删除5
因为队列的限制,只能头删尾加
所以需要将队列的前n-1个元素移动的令一个队列中
-
push
尾加一致
-
-
原理
将队列的前n-1个元素移动到另一个队列,此时可以操纵队尾元素
-
实现
class MyStack: def __init__(self): """ Initialize your data structure here. """ self._queue_b = [] self._queue_a = [] def push(self, x: int) -> None: """ Push element x onto stack. """ self._queue_a.append(x) def pop(self) -> int: """ Removes the element on top of the stack and returns that element. """ if self.empty() return None elif len(self._queue_a) == 1: return self._queue_a.pop(0) else: while len(self._queue_a) != 1: self._queue_b.append(self._queue_a.pop(0)) res = self._queue_a.pop(0) self._queue_a = self._queue_b self._queue_b = [] return res def top(self) -> int: """ Get the top element. """ if self.empty() return None elif len(self._queue_a) == 1: return self._queue_a[0] else: while len(self._queue_a) != 1: self._queue_b.append(self._queue_a.pop(0)) res = self._queue_a.pop(0) self._queue_b.append(res) self._queue_a = self._queue_b self._queue_b = [] return res def empty(self) -> bool: """ Returns whether the stack is empty. """ return len(self._queue_a) == 0
-
-
总结
-
队列,只能头部删除,尾部增加
-
栈,只能在尾部删除和增加
-
无论是队列转栈还是栈转队列要点都是满足各自的特性
-
栈转队列:
要能操纵队头元素
-
队列转栈:
要能操纵队尾元素
-
-
头删 头增 尾删 尾增 栈 × × √ √ 队列转栈 √ × √ √ 队列 √ × × √ 栈转队列 √ × √ √
-
两个栈转队列 两个队列转栈
最新推荐文章于 2024-03-10 21:02:31 发布
本文介绍了如何使用两个栈实现队列,以及两个队列实现栈的方法。栈转队列的关键在于能操纵队头元素,而队列转栈则需要能操纵队尾元素。在实现过程中,通过巧妙地操作栈和队列的特性,成功实现了两者之间的转换。
摘要由CSDN通过智能技术生成