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
}
相关推荐
不会聊天真君6471 小时前
基础语法·中(golang笔记第二期)
开发语言·笔记·golang
zdl6862 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
老鼠只爱大米3 小时前
LeetCode经典算法面试题 #295:数据流的中位数(双堆法、有序列表、平衡树等多种实现方案详解)
算法·leetcode·优先队列··数据流·中位数·java 面试题
x_xbx3 小时前
LeetCode:215. 数组中的第K个最大元素
数据结构·算法·leetcode
FatHonor4 小时前
【golang学习之旅】使用VScode安装配置Go开发环境
vscode·学习·golang
进击的荆棘4 小时前
优选算法——分治
数据结构·算法·leetcode·分治
木井巳5 小时前
【递归算法】找出所有子集的异或总和再求和
java·算法·leetcode·决策树·深度优先
ん贤5 小时前
AI大模型落地系列:一文读懂 Eino 的 Memory 与 Session(持久化对话)
大数据·ai·golang·eino
Aaswk6 小时前
回溯算法的本质理解
c语言·算法·leetcode·力扣·剪枝
迷海6 小时前
力扣原题《分发糖果》,采用二分原则,纯手搓,待验证
c++·算法·leetcode