package main import "fmt" type StackNode struct { Data interface{} //數據 Next *StackNode //下一個節點 } //建立鏈棧 func CreateStack(Data ...interface{}) *StackNode { if len(Data) == 0 { return nil } s := new(StackNode) //記錄下一個節點 var nextNode *StackNode = nil for _, v := range Data { //1,2,3,4,5 //建立新節點存儲數據 newNode := new(StackNode) newNode.Data = v s = newNode //若是下一個節點不爲空 將當前節點的下一個節點設置上一次節點 //if nextNode != nil { s.Next = nextNode //} //下一個節點爲當前節點 nextNode = s } return s } //打印鏈棧 func PrintStack(s *StackNode) { if s == nil { return } for s != nil { fmt.Print(s.Data, " ") s = s.Next } } //鏈棧個數 func LengthStack(s *StackNode) int { if s == nil { return -1 } //循環計算鏈棧個數 i := 0 for s != nil { i++ s = s.Next } return i } //入棧 func Push(s *StackNode, Data interface{}) *StackNode { if s == nil { return nil } if Data == nil { return s } //新建節點 newNode := new(StackNode) newNode.Data = Data newNode.Next = s return newNode } //出棧 func Pop(s *StackNode) *StackNode { if s == nil { return nil } nextNode := s.Next s.Next = nil return nextNode } //清空鏈棧 func Clear(s *StackNode) *StackNode { return nil }