栈的模拟(LeetCode刷题用法)
func main() {stack := make([]string, 0)stack = append(stack, "1" )stack = append(stack, "2" )stack = append(stack, "3" )fmt.Println(stack)stack = stack[:len(stack)-1]fmt.Println(stack)
}
[1 2 3]
[1 2]
以下不用阅读
Invalid operation: i-ind (mismatched types int and interface{})
LeetCode 739实现
golang没有设计stack类型吗?
答案是有的!使用list(双链表)的部分操作就可以达到stack操作的目的。
stack := list.New() //初始化栈
ind := stack.Remove(stack.Front()).(int) //出栈
stack.PushFront(i) //入栈
fmt.Println(stack.Front().Value)
但是为什么需要.(int)的类型断言?给stack传入的本来就是int类型的
// golang list源码
type Element struct {next, prev *Elementlist *ListValue interface{}
}
可以看到Value是 interface{}类型的变量。所以不进行转换调用会报错 会报错因为content是interface{}类型, 而不是int类型(Invalid operation: i-ind (mismatched types int and interface{}))
通过断言实现了类型转换。
参考资料
https://studygolang.com/articles/4276