Python中如何用栈实现队列

发布时间:2021-10-26 10:49:30 作者:柒染
来源:亿速云 阅读:151

Python中如何用栈实现队列,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

用栈实现队列

题目:

使用栈实现队列的下列操作:

Implement the following operations of a queue using stacks.

示例:

MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2); 
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

说明:

Notes:

解题思路:

队列先进后出,栈后进先出。用栈实现队列,可以用两个栈完成题解。入队列时用 stack1 存入节点,出队列时 stack1 内节点顺序出栈压入 stack2 中。

例如 1, 2, 3 元素顺序入队列 
即存入栈stack1:[1, 2, 3]
出队列时顺序应为:1->2->3
但是栈先进先出,出栈顺序为:3->2->1
与出队列顺序不相符
借助另一个栈stack2
stack1内的元素顺序出栈并压入stack2
stack1:[1, 2, 3] ---> stack2:[3, 2, 1]
此时stack2出栈顺序:1->2->3
与出队列顺序相符

【注意】:在出队列时无需着急将 stack1 中的节点顺序压入 stack2。因为要实现的队列是先进后出,可以将 stack2 中的节点全部弹出之后 再将 stack1 内节点顺序压入stack2,这样可以将出栈的时间复杂度摊还到 O(1)。

Java:

class MyQueue {
 private Stack<Integer> stack1;
 private Stack<Integer> stack2;
 public MyQueue() {
 stack1 = new Stack<>();
 stack2 = new Stack<>();
 }
 public void push(int x) {
 stack1.push(x);
 }
 public int pop() {
 if (stack2.isEmpty()) {
 while (!stack1.isEmpty()) {
 stack2.push(stack1.pop());
 }
 }
 return stack2.pop();
 }
 public int peek() {
 //stack1节点顺序弹出并压入stack2
 if (stack2.isEmpty()) {//条件是: stack2为空,而不是stack1非空, 这样摊还复杂度O(1)
 while (!stack1.isEmpty()) {
 stack2.push(stack1.pop());//stack1弹出节点并压入stack2
 }
 }
 return stack2.peek();
 }
 public boolean empty() {
 return stack1.isEmpty() && stack2.isEmpty();
 }
}

Python:

Python语言没有栈和队列数据结构,只能用数组 List 或双端队列 deque 实现。

这类编程语言就压根不需要 用队列实现栈或用栈实现队列这种问题,因为栈和队列本身就必须借助List、deque实现。

所以这道题在这种语言中这就非常简单了,可以说是作弊。

class MyQueue:
 def __init__(self):
 self.queue = []
 def push(self, x: int) -> None:
 self.queue.append(x)
 def pop(self) -> int:
 #弹出第一个元素
 return self.queue.pop(0)
 def peek(self) -> int:
 #返回第一个元素
 return self.queue[0]
 def empty(self) -> bool:
 return not self.queue

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 什么是栈,队列
  2. 用栈实现队列和用队列实现栈

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:Linux命令行如何配置Wi-Fi

下一篇:Linux中lsof命令怎么用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》