Go数据结构与算法-实现栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yang731227/article/details/85059666

title: Go数据结构与算法-实现栈
tags: go,算法


介绍

栈(stack),是一种特殊的线性表,仅能在线性表的一端操作,栈顶允许操作,栈底不允许操作。

栈的特性:后进先出

演示

package main

import (
	"errors"
	"fmt"
)

type  StackArray interface{
	Clear()
	Size()int
	Pop() interface{}
	Push(data interface{})
	isEmpty() bool
	isFull() bool
}

type ArrayList struct{
	dataStore []  interface{}
	theSize  int
}

func  New() *ArrayList{
	list:=new(ArrayList)
	list.dataStore=make([]interface{},0,10) //分配内存10个数组元素

	list.theSize=0  //0
	//fmt.Println("new",list.theSize,cap(list.dataStore))
	return list
}

func(list *ArrayList)  Append (newval  interface{}){

	//list.checkmemisfull()
	list.dataStore=append(list.dataStore,newval) //数据叠加
	//fmt.Println(list.theSize,cap(list.dataStore))
	//list.dataStore[list.theSize]=newval  //赋值
	list.theSize++ //索引移动
}



func (list *ArrayList )Remove(index int)error {
	if index <0 || index >=list.theSize{
		return errors.New("索引越界")
	}

	list.dataStore=append(list.dataStore[:index],list.dataStore[index+1:]...) //删除
	list.theSize--
	return  nil
}

func (list *ArrayList )Clear() {
	list.dataStore=make([]interface{},0,10) //清空
	list.theSize=0
}



type  Stack struct{
	myarray * ArrayList
	capsize int
}


func  NewStack()*Stack{
	mystack:=new(Stack)
	mystack.myarray=New()
	mystack.capsize=10  //0
	return mystack
}



func (mystack  *Stack) Clear(){
	mystack.myarray.Clear()
	mystack.myarray.theSize=0
}
func (mystack  *Stack) Size()int {
	return mystack.myarray.theSize
}
func (mystack  *Stack) isEmpty() bool{
	if mystack.myarray.theSize==0{
		return true
	}else{
		return false
	}
}
func (mystack  *Stack)  isFull() bool{
	if mystack.capsize==mystack.myarray.theSize{
		return true
	}else{
		return false
	}
}
func (mystack  *Stack)  Pop() interface{}{
	if !mystack.isEmpty(){
		last:=mystack.myarray.dataStore[mystack.myarray.theSize-1]
		mystack.myarray.Remove(mystack.myarray.theSize-1)
		return last;
	}
	return nil
}
func (mystack  *Stack)  Push(data interface{}){
	if !mystack.isFull(){
		mystack.myarray.Append(data)
	}
}


func main(){
	mystack :=NewStack()
	mystack.Push(1)
	mystack.Push(2)
	mystack.Push(3)
	mystack.Push(4)
	fmt.Println(mystack.Pop())
	fmt.Println(mystack.Pop())
	fmt.Println(mystack.Pop())
	fmt.Println(mystack.Pop())

}


猜你喜欢

转载自blog.csdn.net/yang731227/article/details/85059666