go stack 数据结构

//stack.go

package stack 

type Stack struct{     //定义栈
	dataStore  []interface{}
	size int
}

func New() *Stack{   // 栈初始化
	s :=new(Stack)
	s.dataStore = make([]interface{},0)
	s.size = 0

	return s 
}

func (s *Stack) Size() int{   //返回栈的大小
	return s.size
}

func (s *Stack) IsEmpty() bool{  //判断栈是否为空
	return s.size == 0
}


func (s *Stack) Push(element interface{}){   //数据入栈操作
	s.dataStore = append(s.dataStore,element)
	s.size++
}


func (s *Stack) Pop() interface{} {   //数据出栈操作
	if(s.IsEmpty()){
		return nil
	}
	last :=s.dataStore[s.Size()-1]
	s.dataStore = s.dataStore[:s.Size()-1]
	s.size--
	return last

}


func (s *Stack) Peak() interface{} {  //取栈顶元素
	if(s.IsEmpty()){
		return nil
	}
	return s.dataStore[s.Size()-1]
}

func (s *Stack) Clear(){   //清空栈元素

	s.dataStore=s.dataStore[:1]
	s.size = 0 
}
//stack_test.go


package stack 

import "testing"


func TestStack(t *testing.T){
	stack :=New()
	if stack.Size()!=0 || !stack.IsEmpty(){
		t.Errorf("the size of stack is not equal 0")
	}

	stack.Push(1)
	stack.Push(3)

	if stack.Size()!=2 {
		t.Errorf("stack push failed!")
	}
	p :=stack.Pop()

	if v,ok :=p.(int);!ok||v!=3||stack.Size()!=1{
		t.Errorf("stack pop failed")
	}

	p2 :=stack.Peak()
	if v,ok :=p2.(int);!ok||v!=1||stack.Size()!=1{
		t.Log("stack peak error")
		t.Fail()
	}

	stack.Clear()
	if !stack.IsEmpty(){
		t.Errorf("stack clear error")
	}
}

发布了123 篇原创文章 · 获赞 71 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/boke14122621/article/details/98482379