From 71a24c5dd88a48d518a3be11ab9b68785c5dc66a Mon Sep 17 00:00:00 2001 From: baici1 <249337001@qq.com> Date: Tue, 31 Aug 2021 15:57:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0225.=20=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88=20go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index afa563e3..8d4db953 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -359,6 +359,71 @@ class MyStack: Go: +```go +type MyStack struct { + queue []int//创建一个队列 +} + + +/** Initialize your data structure here. */ +func Constructor() MyStack { + return MyStack{ //初始化 + queue:make([]int,0), + } +} + + +/** Push element x onto stack. */ +func (this *MyStack) Push(x int) { + //添加元素 + this.queue=append(this.queue,x) +} + + +/** Removes the element on top of the stack and returns that element. */ +func (this *MyStack) Pop() int { + n:=len(this.queue)-1//判断长度 + for n!=0{ //除了最后一个,其余的都重新添加到队列里 + val:=this.queue[0] + this.queue=this.queue[1:] + this.queue=append(this.queue,val) + n-- + } + //弹出元素 + val:=this.queue[0] + this.queue=this.queue[1:] + return val + +} + + +/** Get the top element. */ +func (this *MyStack) Top() int { + //利用Pop函数,弹出来的元素重新添加 + val:=this.Pop() + this.queue=append(this.queue,val) + return val +} + + +/** Returns whether the stack is empty. */ +func (this *MyStack) Empty() bool { + return len(this.queue)==0 +} + + +/** + * Your MyStack object will be instantiated and called as such: + * obj := Constructor(); + * obj.Push(x); + * param_2 := obj.Pop(); + * param_3 := obj.Top(); + * param_4 := obj.Empty(); + */ +``` + + + javaScript: 使用数组(push, shift)模拟队列