Stack & Queue
Posted ybxw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stack & Queue相关的知识,希望对你有一定的参考价值。
232. Implement Queue using Stacks
FILO to FIFO
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // returns 1 queue.pop(); // returns 1 queue.empty(); // returns false
class MyQueue: def __init__(self): self.s1 = [] self.s2 = [] def push(self, x: int) -> None: while self.s1: self.s2.append(self.s1.pop()) self.s1.append(x) while self.s2: self.s1.append(self.s2.pop()) def pop(self) -> int: return self.s1.pop() def peek(self) -> int: return self.s1[-1] def empty(self) -> bool: return not self.s1 # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
class MyQueue: def __init__(self): self.s1 = [] self.s2 = [] def push(self, x: int) -> None: self.s1.append(x) def pop(self) -> int: self.peek() return self.s2.pop() def peek(self) -> int: if not self.s2: while self.s1: self.s2.append(self.s1.pop()) return self.s2[-1] def empty(self) -> bool: return not self.s1
225. Implement Stack using Queues
FIFO to FILO
MyStack stack = new MyStack(); stack.push(1); stack.push(2); stack.top(); // returns 2 stack.pop(); // returns 2 stack.empty(); // returns false
class Stack: def __init__(self): self._queue = collections.deque() def push(self, x): q = self._queue q.append(x) for _ in range(len(q) - 1): q.append(q.popleft()) def pop(self): return self._queue.popleft() def top(self): return self._queue[0] def empty(self): return not len(self._queue)
以上是关于Stack & Queue的主要内容,如果未能解决你的问题,请参考以下文章