LeetCode 0225.用队列实现栈【Go】

简介: LeetCode 0225.用队列实现栈【Go】

用队列实现栈

LeetCode225. 用队列实现栈

题目描述

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

注意:

  • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsizeis empty 这些操作。
  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:

MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

提示:

  • 1 <= x <= 9
  • 最多调用100pushpoptopempty
  • 每次调用 poptop 都保证栈不为空

思路

题目要求

  • 用两个队列来实现栈,该栈类具有四个方法:压栈、弹栈、返回栈顶元素、判断栈空

队列是先进先出,栈是先后进先出。用队列模拟栈,其实一个队列就够了

压栈就是将元素放入队尾;弹栈就是取出队尾元素;返回栈顶元素就是返回队尾元素;队列中没有元素即栈空。

代码

Go

// MyStack 栈类
type MyStack struct {
  queue []int
}
// Constructor 构造方法
func Constructor() MyStack {
  queue := make([]int, 0)
  return MyStack{queue}
}
// Push 压栈
func (this *MyStack) Push(x int) {
  this.queue = append(this.queue, x)
}
// Pop 弹栈
func (this *MyStack) Pop() int {
  result := this.queue[len(this.queue)-1]
  this.queue = this.queue[:len(this.queue)-1]
  return result
}
// Top 返回栈顶元素
func (this *MyStack) Top() int {
  return this.queue[len(this.queue)-1]
}
// Empty 判断栈空
func (this *MyStack) Empty() bool {
  if len(this.queue) == 0 {
    return true
  }
  return false
}

Link

GitHub

目录
相关文章
|
1天前
LeetCode 热题100——单调栈
LeetCode 热题100——单调栈
19 0
|
1天前
|
Go C++
【力扣】2696. 删除子串后的字符串最小长度(模拟 栈 C++ Go实现栈)
【2月更文挑战第18天】2696. 删除子串后的字符串最小长度(模拟 栈 C++ Go实现栈)
35 6
|
1天前
【Leetcode 2487】从链表中移除节点 —— 单调栈
解题思路:维持一个单调递增栈,当栈为空时,记录当前节点为头节点;否则当前节点为栈顶节点的后继节点
|
1天前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
6 0
|
1天前
|
C语言
Leetcode每日一题——“用栈实现队列”
Leetcode每日一题——“用栈实现队列”
|
1天前
|
C语言
Leetcode每日一题——“用队列实现栈”
Leetcode每日一题——“用队列实现栈”
|
1天前
|
存储
leetcode1944. 队列中可以看到的人数
leetcode1944. 队列中可以看到的人数
16 0
|
1天前
|
算法 安全 Java
【数据结构与算法】6、栈(Stack)的实现、LeetCode:有效的括号
【数据结构与算法】6、栈(Stack)的实现、LeetCode:有效的括号
22 0
|
1天前
|
容器
代码随想录 Day49 单调栈01 LeetCode LeetCodeT739每日温度 T496 下一个最大元素I
代码随想录 Day49 单调栈01 LeetCode LeetCodeT739每日温度 T496 下一个最大元素I
35 0
|
1天前
代码随想录Day29 贪心04 LeetCode T860 柠檬水找零 T406 根据身高重建队列 T452 用最少得箭引爆气球
代码随想录Day29 贪心04 LeetCode T860 柠檬水找零 T406 根据身高重建队列 T452 用最少得箭引爆气球
25 0