1. 基于切片的实现
package main
import (
"fmt"
)
var stackArray []interface{}
var a []int
func push(x interface{}) {
stackArray = append(stackArray, x)
}
func pop() interface{} {
sz := len(stackArray)
ele := stackArray[sz-1]
stackArray = stackArray[:sz-1]
return ele
}
func peek() interface{} {
return stackArray[length()-1]
}
func length() int {
return len(stackArray)
}
func isEmpty() bool {
return length() == 0
}
func main() {
push(1)
push(2)
push(3)
fmt.Println(stackArray)
fmt.Println(pop())
fmt.Println(peek())
push("hello")
push(3.14)
fmt.Println(peek())
fmt.Println(pop())
fmt.Println(peek())
}
2. 基于链表的实现
package main
import (
"fmt"
)
type Node struct {
Val interface{}
Next *Node
}
type Stack struct {
top *Node
sz int
}
func (st *Stack) push(x interface{}) {
newNode := &Node{}
newNode.Val = x
newNode.Next = st.top
st.top = newNode
st.sz++
}
func (st *Stack) pop() interface{} {
ele := st.top.Val
st.top = st.top.Next
st.sz--
return ele
}
func (st *Stack) peek() interface{} {
ele := st.top.Val
return ele
}
func (st *Stack) size() int {
return st.sz
}
func (st *Stack) isEmpty() bool {
return st.size() == 0
}
func (st *Stack) show() {
for cur := st.top; cur != nil; cur = cur.Next {
fmt.Print(cur.Val)
if cur.Next != nil {
fmt.Print("<-")
}
}
fmt.Println()
}
func main() {
st := &Stack{}
st.push("aaa")
st.push("bbb")
st.push("ccc")
st.show()
fmt.Println(st.size())
fmt.Println(st.pop())
fmt.Println(st.pop())
fmt.Println(st.size())
fmt.Println(st.pop())
fmt.Println(st.isEmpty())
}
|