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

本文详细介绍如何使用Go语言实现栈这一特殊线性表数据结构。栈遵循后进先出原则,只允许在一端进行插入和删除操作。文章通过具体代码演示了栈的基本操作,包括创建、压栈、弹栈、检查是否为空及满等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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())

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值