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
}
相关推荐
灯澜忆梦16 分钟前
【基于GO的Web开发4】html/template 模板语法
后端·golang·html
圣保罗的大教堂35 分钟前
leetcode 1386. 安排电影院座位 中等
leetcode
Nil2081 小时前
leetcode 146LRU缓存
算法·leetcode·缓存
rannn_1112 小时前
【力扣hot100】图论专题+模板|DFS、BFS、拓扑排序...
java·算法·leetcode·深度优先·图论
圣殿骑士-Khtangc2 小时前
Go-Kubernetes-Client-go编程从Pod管理到CRD开发
golang
学习星球3 小时前
【LeetCode算法题精讲】二分查找精讲
java·数据结构·算法·leetcode·职场和发展·图搜索
路多辛4 小时前
一个 Go 写的全能 AI Agent,讲讲 covo-agent
java·开发语言·golang
To_OC13 小时前
LC 239 滑动窗口最大值:从暴力超时到单调队列一遍过
javascript·算法·leetcode
.道阻且长.14 小时前
9.LeetCode算法习题讲解--滑动窗口--无重复字符的最长字串
算法·leetcode·职场和发展·哈希算法
圣殿骑士-Khtangc15 小时前
Go-Prometheus指标采集与监控全栈实践
golang