github.com/searKing/golang/go@v1.2.117/container/stack/stack.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package stack 6 7 import "container/list" 8 9 // take advantage of list 10 type ( 11 Stack struct { 12 list list.List 13 } 14 // Element is an element of a linked list. 15 Element list.Element 16 ) 17 18 // New creates a new stack 19 func New() *Stack { 20 return &Stack{} 21 } 22 23 // Len returns the number of items in the stack 24 func (s *Stack) Len() int { 25 return s.list.Len() 26 } 27 28 // Peek view the top item on the stack 29 func (s *Stack) Peek() *Element { 30 return (*Element)(s.list.Back()) 31 } 32 33 // Pop the top item of the stack and return it 34 func (s *Stack) Pop() *Element { 35 ele := s.list.Back() 36 if ele == nil { 37 return nil 38 } 39 s.list.Remove(ele) 40 return (*Element)(ele) 41 } 42 43 // Push a value onto the top of the stack 44 func (s *Stack) Push(value any) *Element { 45 return (*Element)(s.list.PushBack(value)) 46 }