数据结构和算法-go 切片实现栈和队列
type Stack struct {
list []interface{}
}
func NewStack() *Stack{
return new(Stack)
}
func (s *Stack) Push(value interface{}) {
s.list = append(s.list, value)
}
func (s *Stack) Pop () interface{}{
len := len(s.list)
var value interface{}
if len==0 {
return nil
}else if len==1{
value = s.list[0]
s.list = []interface{}{}
}else{
value = s.list[len-1]
s.list = s.list[len-2:len-1]
}
return value
}
func (s *Stack) Print() {
for _,v := range s.list {
fmt.Printf("%v",v)
}
fmt.Printf("\n")
}
func main(){
stack := NewStack()
stack.Push(1)
stack.Push(2)
res1:= stack.Pop()
res2:= stack.Pop()
res3:= stack.Pop()
fmt.Println(res1,res2,res3)
}
func main() {
q := NewQueue()
q.Push(12)
q.Push(15)
q.Pop()
q.Print()
}
type Queue struct {
list []interface{}
}
func NewQueue() *Queue{
list := make([]interface{},0)
return &Queue{list:list}
}
func (q *Queue)Push(data interface{}) {
q.list = append(q.list,data)
}
func (q *Queue)Pop() interface{}{
if len(q.list)==0 {
return nil
}
res := q.list[0]
q.list = q.list[1:]
return res
}
func (q *Queue)Print(){
for _,val := range q.list {
fmt.Println(val)
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: