使用栈实现队列的下列操做:程序员
push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。
示例:算法
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false
说明:app
设计时使用两个栈
一个栈做为压入栈,记为stack_in
一个栈做为弹出栈,记为stack_out设计
1.当有数据入队列时,压入stack_incode
2.当有数据出队列时,从stack_out弹出,若是stack_out为空,则循环遍历stack_in,将stack_in中的元素所有弹出,并按弹出顺序所有压入栈stack_out,循环结束后从stack_out弹出栈顶元素便可队列
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) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if not self.stack_out: while self.stack_in: self.stack_out.append(self.stack_in.pop()) return self.stack_out.pop() else: return self.stack_out.pop() def peek(self) -> int: """ Get the front element. """ if not self.stack_out: while self.stack_in: self.stack_out.append(self.stack_in.pop()) return self.stack_out[-1] else: return self.stack_out[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ if self.stack_out or self.stack_in: return False else: return True
入队内存
时间复杂度:O(1):向栈压入元素的时间复杂度为O(1)element
空间复杂度:O(n):须要额外的内存来存储队列元素it
出队class
时间复杂度: 摊还复杂度 O(1),最坏状况下的时间复杂度 O(n)
在最坏状况下,stack_out为空,算法须要从 stack_in 中弹出 n 个元素,而后再把这 n个元素压入 stack_out
空间复杂度 :O(1)
公众号:《程序员养成记》
主要写算法、计算机基础之类的文章, 有兴趣来关注一块儿成长!