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
}
相关推荐
cpp_25016 小时前
P2708 硬币翻转
数据结构·c++·算法·题解·洛谷
IT=>小脑虎7 小时前
Go语言零基础小白学习知识点【基础版详解】
开发语言·后端·学习·golang
源代码•宸7 小时前
Golang语法进阶(并发概述、Goroutine、Channel)
服务器·开发语言·后端·算法·golang·channel·goroutine
踩坑记录7 小时前
leetcode hot100 11.盛最多水的容器 medium 双指针
算法·leetcode·职场和发展
WayneJoon.H7 小时前
2023CISCN go_session
网络安全·golang·ctf·代码审计·ciscn
圣保罗的大教堂7 小时前
leetcode 865. 具有所有最深节点的最小子树 中等
leetcode
-曾牛9 小时前
Yak语言核心基础:语句、变量与表达式详解
数据库·python·网络安全·golang·渗透测试·安全开发·yak
X在敲AI代码9 小时前
LeetCode 基础刷题D2
算法·leetcode·职场和发展
源代码•宸9 小时前
Leetcode—1929. 数组串联&&Q1. 数组串联【简单】
经验分享·后端·算法·leetcode·go
weixin_461769409 小时前
15. 三数之和
c++·算法·leetcode·三数之和