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
}
相关推荐
夏幻灵10 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG11 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z12 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
圣保罗的大教堂13 小时前
leetcode 301. 删除无效的括号 困难
leetcode
北冥you鱼14 小时前
Go 语言空接口(interface{})使用场景与最佳实践
开发语言·windows·golang
夏幻灵15 小时前
每日一题:LeetCode 206:反转链表——三指针与原地反转详解
算法·leetcode·链表
徐小黑ACG17 小时前
Golang 基础06 接口interface
开发语言·后端·golang
小小龙学IT17 小时前
Go 语言 cgo 与 C/C++ 互操作深度解析:从 fwlib 直连到工业数采网关实战系列
c语言·c++·golang
牛奔18 小时前
mise 管理多版本 Go 项目
开发语言·前端·chrome·后端·golang
Tisfy18 小时前
LeetCode 0301.删除无效的括号:二进制枚举 / 回溯
算法·leetcode·字符串·题解·回溯·括号匹配·二进制枚举