package main import ( "fmt" "os" ) type Node struct { val int pNode *Node } type Stack struct { pTop,pBottom *Node } func initStack(pStack *Stack){ pNew:=new(Node) pNew.pNode=nil pStack.pTop=pNew pStack.pBottom=pNew if pStack.pTop==nil || pStack.pBottom==nil { fmt.Println("分配头节点内存失败,程序退出") os.Exit(-1) } } func push(pStack *Stack,val int) { pNew:=new(Node) pNew.val=val if pNew==nil { fmt.Println("分配头节点内存失败,程序退出") os.Exit(-1) } pNew.pNode=pStack.pTop pStack.pTop=pNew } func pop(pStack *Stack)(bool ,int) { if isempty(pStack) { return false,0 } reval:=pStack.pTop.val pStack.pTop=pStack.pTop.pNode return true,reval } func isempty(pStack *Stack)bool { if pStack.pTop==pStack.pBottom{ return true } return false } func traverse(pStack *Stack){ if isempty(pStack) { return } p:=pStack.pTop for ;p!=pStack.pBottom;p=p.pNode { fmt.Printf("%d ",p.val) } fmt.Println() } func clear(pStack *Stack){ if isempty(pStack) { return } pStack.pTop=pStack.pBottom } func main() { var pstack Stack initStack(&pstack) rebool,reval:=pop(&pstack) if rebool { fmt.Printf("出栈成功,出栈值为:%d\n",reval) } else { fmt.Println("出栈出错") } traverse(&pstack) clear(&pstack) traverse(&pstack) }
有疑问加站长微信联系(非本文作者)