每个专题5道,一天一道

232. 用栈实现队列

地址:https://leetcode-cn.com/problems/implement-queue-using-stacks/

解题思路1

两个数据结构的概念:

  • 栈:后进先出
  • 队列:先进先出

题目让我们用两个栈来实现一个队列,就是要让两个栈实现一个先进先出的数据结构。

思路:

「输入栈」会把输入顺序颠倒;如果把「输入栈」的元素逐个弹出放到「输出栈」,再从「输出栈」弹出元素的时候,则可以负负得正,实现了先进先出。

具体做法:

  1. 可以把一个栈当做「输入栈」,把另一个栈当做「输出栈」。
  2. 当 push() 新元素的时候,放到「输入栈」的栈顶,记此顺序为「输入序」。
  3. 当 pop() 元素的时候,是从「输出栈」弹出元素。如果「输出栈」为空,则把「输入栈」的元素逐个 pop() 并且 push() 到「输出栈」中,这一步会把「输入栈」的栈底元素放到了「输出栈」的栈顶。此时负负得正,从「输出栈」的 pop() 元素的顺序与「输入序」相同。
type MyQueue struct {stack1,stack2 []int
}/** Initialize your data structure here. */
func Constructor() MyQueue {return MyQueue{}
}/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {this.stack1 = append(this.stack1,x)
}func (this *MyQueue) in2out(){for len(this.stack1) > 0 {this.stack2 = append(this.stack2,this.stack1[len(this.stack1)-1])this.stack1 = this.stack1[:len(this.stack1)-1]}
}/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {if len(this.stack2) == 0 {this.in2out()}x := this.stack2[len(this.stack2)-1]this.stack2 = this.stack2[:len(this.stack2)-1]return x
}/** Get the front element. */
func (this *MyQueue) Peek() int {if len(this.stack2) == 0{this.in2out()}return this.stack2[len(this.stack2)-1]
}/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {return len(this.stack1)==0 && len(this.stack2)==0
}/*** Your MyQueue object will be instantiated and called as such:* obj := Constructor();* obj.Push(x);* param_2 := obj.Pop();* param_3 := obj.Peek();* param_4 := obj.Empty();*/
class MyQueue {private:stack<int> stack1,stack2;void in2out(){while(!stack1.empty()){stack2.push(stack1.top());stack1.pop();}}public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {stack1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {if(stack2.empty()){in2out();}int x = stack2.top();stack2.pop();return x;}/** Get the front element. */int peek() {if(stack2.empty()){in2out();}return stack2.top();}/** Returns whether the queue is empty. */bool empty() {return stack1.empty() &&  stack2.empty(); }
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/
class MyQueue:def __init__(self):"""Initialize your data structure here."""self.stack1 = []self.stack2 = []def push(self, x: int) -> None:"""Push element x to the back of queue."""self.stack1.append(x)def pop(self) -> int:"""Removes the element from in front of queue and returns that element."""if not self.stack2:while self.stack1:self.stack2.append(self.stack1.pop())return self.stack2.pop()def peek(self) -> int:"""Get the front element."""if not self.stack2:while self.stack1:self.stack2.append(self.stack1.pop())return self.stack2[-1]def empty(self) -> bool:"""Returns whether the queue is empty."""return not self.stack1 and not self.stack2# 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()

时间复杂度:push() 时间复杂度是 O(1);peek()/pop() 均摊时间复杂度是 O(1),单步操作的最坏时间复杂度是 O(N)。
空间复杂度:空间复杂度是 O(N),因为总的占用了 NN 个元素的空间。

LeetCode栈专题-1(go/py3/c++)相关推荐

  1. leetcode探索专题中的初级算法练习题(python代码+解题思路)

    本文记录leetcode探索专题中的初级算法练习题,附python实现代码&解题思路,做题过程不免查阅网络资料,侵删~如有错误,欢迎指正交流! 目录 专题一:数组: 26.从排序数组中删除重复 ...

  2. 写出一段代码将链表中的两个节点位置互换位置_面试 leetcode 算法专题系列(二)—— 链表...

    前言:只照着常考题去刷题确实是一种方法.但调研之后发现自己还是考虑不周,刷题刷的不应该是题,而是解题的思路和熟练程度.于是我决定重新组织一下刷题笔记的讲解顺序,不再以面试常考题来刷.而是以面试出题频率 ...

  3. leetcode(链表专题)

    数组模拟链表 #include<iostream> using namespace std;const int N = 100; // 单链表 // head存储链表头,e[]存储节点的值 ...

  4. leetcode算法专题训练:十四.位操作专题

    文章目录 十四.位操作专题 50.Pow(x,n) 69.x的平方根 136.只出现一次的数字 137.只出现一次的数字2 260.只出现一次的数字3 89.格雷编码 剑指 Offer 64. 求1+ ...

  5. 【Leetcode栈与队列】1047.删除字符串中的所有相邻重复项 6120.数组能形成多少数对(一些题外话和做题经验!!看作对对碰游戏!!)

    文章目录 题外话 1.游戏开发可能使用栈结构 2.编程语言的一些功能实现也会使用栈结构 Leetcode 1047.删除字符串中的所有相邻重复项 1.问题描述 2.解决方案 Leetcode 6120 ...

  6. leetcode 栈 II

    栈 880. 索引处的解码字符串 895. 最大频率栈 901. 股票价格跨度 907. 子数组的最小值之和 921. 使括号有效的最少添加 946. 验证栈序列 962. 最大宽度坡* 1003. ...

  7. leetcode 栈739. 每日温度

    739. 每日温度 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数.如果之后都不会升高,请输入 0 来代替.例如,给定一个列表 temperatures ...

  8. LeetCode栈和队列练习

    文章目录 前言 1.力扣20. 有效的括号 1.题目分析 2.代码示现 2.力扣225. 用队列实现栈 1.题目分析 2.代码实现 3.力扣232. 用栈实现队列 1.题目分析 2.代码实现 4.力扣 ...

  9. 【LeetCode】专题一 二叉树层序遍历

    二叉树层序遍历 在本文中,我将会选取LeetCode上二叉树层序遍历的多道例题,并给出解答,通过多道题我们就可以发现,二叉树的层序遍历并不复杂,并且有着共通点. 102. 二叉树的层序遍历 给你二叉树 ...

最新文章

  1. css3中transition属性详解
  2. RabbitMQ入门教程——.NET客户端使用
  3. OC开发_Storyboard——MapKit
  4. 如何使用jstack分析线程状态
  5. Vue.js2.0开发环境搭建(二)
  6. 指纹对比软件_iQOO VS 小米9屏幕指纹大对决,这次我为vivo疯狂打Call!
  7. Android开发(1):随机绘制彩色实心圆
  8. 一图读懂基于鲲鹏处理器的全栈混合云华为云Stack6.5
  9. python将一个文件的内容写入另一个文件_Python3中如何将文件中两个关键词中的信息写入到另一文件?...
  10. AudioBuffer
  11. 8个Python高效数据分析的技巧
  12. auto.js适合安卓小米6,朋友圈触控点赞
  13. Lesson 04 for Plotting in R for Biologists
  14. MFC无界面后台运行程序
  15. springmvc/ssm框架详细图文解说流程图及运行原理_附源码
  16. x86系统引导(1)
  17. 旧手机改装服务器——Android上的Linux(linux deploy)
  18. U盘等无法弹出的解决办法
  19. php邮箱接收代码,PHP使用POP3读取邮箱接收邮件
  20. 【C语言】关于数组传参问题/首地址

热门文章

  1. Spring Data MongoDB示例
  2. 消费者驱动的契约测试 Spring Cloud Contract介绍
  3. 排序算法理解总结篇——冒泡排序、选择排序、插入排序、希尔排序、归并排序、堆排序、计数排序、基数排序、桶排序
  4. 腾讯云432元撸4年2H4G6M云服务器
  5. 爬虫究竟是合法还是违法的?
  6. C#算法设计排序篇之08-计数排序(附带动画演示程序)
  7. freecodecamp_关于freeCodeCamp-常见问题
  8. 什么是客户旅程_为什么记录您的旅程将导致开发人员成功
  9. 网络爬虫数据挖掘_我如何构建无服务器网络爬虫以大规模挖掘温哥华房地产数据...
  10. 自然语言处理实践Task2