Golang | Leetcode Golang题解之第225题用队列实现栈

题目:

题解:

Go 复制代码
type MyStack struct {
    queue []int
}

/** Initialize your data structure here. */
func Constructor() (s MyStack) {
    return
}

/** Push element x onto stack. */
func (s *MyStack) Push(x int) {
    n := len(s.queue)
    s.queue = append(s.queue, x)
    for ; n > 0; n-- {
        s.queue = append(s.queue, s.queue[0])
        s.queue = s.queue[1:]
    }
}

/** Removes the element on top of the stack and returns that element. */
func (s *MyStack) Pop() int {
    v := s.queue[0]
    s.queue = s.queue[1:]
    return v
}

/** Get the top element. */
func (s *MyStack) Top() int {
    return s.queue[0]
}

/** Returns whether the stack is empty. */
func (s *MyStack) Empty() bool {
    return len(s.queue) == 0
}
相关推荐
Java成神之路-1 小时前
【LeetCode 刷题笔记】34. 在排序数组中查找元素的第一个和最后一个位置 | 二分查找经典刷题题解
算法·leetcode
会编程的土豆7 小时前
由c/c++速通go语言,新手必看
c语言·c++·golang
念何架构之路12 小时前
Go Socket编程
开发语言·后端·golang
承渊政道13 小时前
【动态规划算法】(完全背包问题从状态定义到空间优化)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
超级大福宝13 小时前
【力扣48. 旋转图像】超好记忆版 + 口诀
c++·算法·leetcode
codeejun13 小时前
每日一Go-59、云原生入门为什么一定要学Docker?
docker·云原生·golang
人道领域14 小时前
【LeetCode刷题日记】掌握二叉树遍历:栈实现的三种绝妙方法
算法·leetcode·职场和发展
阿Y加油吧14 小时前
二刷 LeetCode:动态规划经典双题复盘
算法·leetcode·动态规划
莫等闲-15 小时前
代码随想录一刷记录Day44——leetcode1143.最长公共子序列 53. 最大子序和
数据结构·c++·算法·leetcode·动态规划
初心未改HD15 小时前
gRPC 与 Protobuf 实战指南
开发语言·golang