剑指Offer 09 用两个栈实现队列(go语言实现链表栈)

原题地址:

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
在这里插入图片描述

解题的思路为,s1栈用于入队,当需要出队时,将s1栈元素依次出栈入栈到s2栈,然后由s2栈出栈即可。这题的特别之处在于,我觉得go语言标准库中的list并不是特别好用,耗时比较高,因此自己实现了链表栈。当然我选择的是链表栈,也可以使用切片来实现顺序栈。

type CQueue struct {
    
    
    S1,S2 *Stack
}

type Stack struct{
    
    
    Pre *Stack
    Val int
}

//需要使用两层指针,第一层指针可以改变指针指向的Stack节点的值
//而第二层指针可以改变指针指向的Stack节点
//因为栈需要改变栈顶指针指向最新的元素,所以需要改变指针的指向
//所以使用了双层指针
func Push(s **Stack,val int){
    
    
    n := new(Stack)
    n.Val = val
    n.Pre = *s
    *s = n
}
func Pop(s **Stack)int{
    
    
    res := (*s).Val
    *s = (*s).Pre
    return res
}

func Constructor() CQueue {
    
    
    return CQueue{
    
    }
}


func (this *CQueue) AppendTail(value int)  {
    
    
    Push(&this.S1,value)
}


func (this *CQueue) DeleteHead() int {
    
    
    if this.S2 == nil{
    
    
        if this.S1 == nil{
    
    
            return -1
        }
        for this.S1 !=nil{
    
    
            Push(&this.S2,Pop(&this.S1))
        }
        return Pop(&this.S2)
    }else{
    
    
        return Pop(&this.S2)
    }
}


/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */

在这里插入图片描述
272ms用的是标准库的container/list

猜你喜欢

转载自blog.csdn.net/rglkt/article/details/119053576