github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/datastructures/stack/stack.go (about)

     1  // 栈结构
     2  package stack
     3  
     4  import (
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  type IStack interface {
    10  	Len() int
    11  	IsEmpty() bool
    12  	Peek() interface{}
    13  	Pop() interface{}
    14  	Push(value interface{})
    15  	Flush()
    16  }
    17  
    18  type (
    19  	Stack struct {
    20  		top    *node // 栈顶
    21  		length int
    22  	}
    23  
    24  	node struct {
    25  		value interface{}
    26  		pre   *node
    27  	}
    28  )
    29  
    30  func New() *Stack {
    31  	return &Stack{nil, 0}
    32  }
    33  
    34  func (s *Stack) Len() int {
    35  	return s.length
    36  }
    37  
    38  func (s *Stack) IsEmpty() bool {
    39  	return s.length == 0
    40  }
    41  
    42  func (s *Stack) Peek() interface{} {
    43  	if s.length == 0 {
    44  		return nil
    45  	}
    46  	return s.top.value
    47  }
    48  
    49  func (s *Stack) Pop() interface{} {
    50  	if s.length == 0 {
    51  		return nil
    52  	}
    53  	n := s.top
    54  	s.top = n.pre
    55  	s.length--
    56  	return n.value
    57  }
    58  
    59  func (s *Stack) Push(value interface{}) {
    60  	n := s.top
    61  	s.top = &node{value, n}
    62  	s.length++
    63  }
    64  
    65  func (s *Stack) Flush() {
    66  	s.length = 0
    67  	s.top = nil
    68  }
    69  
    70  func (s *Stack) String() string {
    71  	var sb strings.Builder
    72  	sb.WriteString("top ")
    73  	cur := s.top
    74  	for ; cur != nil; cur = cur.pre {
    75  		_, _ = fmt.Fprintf(&sb, "%v ", cur.value)
    76  	}
    77  	return sb.String()
    78  }