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
}
相关推荐
执着2592 小时前
力扣hot100 - 199、二叉树的右视图
数据结构·算法·leetcode
清云随笔3 小时前
Golang基础
golang
cpp_25013 小时前
P8448 [LSOT-1] 暴龙的土豆
数据结构·c++·算法·题解·洛谷
YGGP3 小时前
【Golang】LeetCode 49. 字母异位词分组
leetcode
唐梓航-求职中3 小时前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
YGGP3 小时前
【Golang】LeetCode 1. 两数之和
leetcode
唐梓航-求职中3 小时前
编程大师-技术-算法-leetcode-355. 设计推特
算法·leetcode·面试
唐梓航-求职中3 小时前
技术-算法-leetcode-1606. 找到处理最多请求的服务器(易懂版)
服务器·算法·leetcode
YGGP6 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
牛奔6 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang