golang中用链表实现栈
node通过prev字段进行关联,stack维护栈顶节点
stack.go
package stacktype Stack struct { top *node length int}type node struct { value interface{} prev *node}// 创建一个栈func New() *Stack { return &Stack{nil, 0}}// 取栈长度func (s *Stack) Len() int { return s.length}// 查看栈顶元素func (s *Stack) Peek() interface{} { if s.length == 0 { return nil } return s.top.value}// 出栈func (s *Stack) Pop() interface{} { if s.length == 0 { return nil } n := s.top s.top = n.prev s.length-- return n.value}// 入栈func (s *Stack) Push(value interface{}) { n := &node{value, s.top} s.top = n s.length++}
main.go
package mainimport ( "./stack" "fmt")func main() { st := stack.New() st.Push(111) st.Push(222) fmt.Println(st.Peek(), st.Len()) item := st.Pop() fmt.Println(item) fmt.Println(st.Peek(), st.Len())}
输出:
222 2222111 1
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。