0
点赞
收藏
分享

微信扫一扫

225. 用队列实现栈、Leetcode的Go实现

影子喵喵喵 2022-02-05 阅读 88

225. 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

注意:

示例:

提示:

两个队列:

type MyStack struct {
    s1 []int
    s2 []int
}


func Constructor() MyStack {
    return MyStack{}
}


func (this *MyStack) Push(x int)  {
    // push到s1中
    this.s1=append(this.s1,x)
}


func (this *MyStack) Pop() int {
    // s2作为临时缓存,
    for i:=0;i<len(this.s1)-1;i++{
        this.s2=append(this.s2,this.s1[i])
    }
    res := this.s1[len(this.s1)-1]
    this.s1,this.s2=this.s2,nil
    return res
}


func (this *MyStack) Top() int {
    res := this.Pop()
    this.s1=append(this.s1,res)
    return res
}


func (this *MyStack) Empty() bool {
    if len(this.s1)==0 {
        return true
    }
    return false
}


/**
 * 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();
 */

一个队列:

type MyStack struct {
    stack []int
}


func Constructor() MyStack {
    return MyStack{}
}


func (this *MyStack) Push(x int)  {
    this.stack=append(this.stack,x)
}


func (this *MyStack) Pop() int {
    res := this.stack[len(this.stack)-1]
    this.stack=this.stack[:len(this.stack)-1]
    return res
}


func (this *MyStack) Top() int {
    return this.stack[len(this.stack)-1]
}


func (this *MyStack) Empty() bool {
    if len(this.stack)!=0 {
        return false
    }
    return true
}


/**
 * 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();
 */
举报

相关推荐

0 条评论