golang数据结构-线性表

    线性表时n(n>=0)个元素构成的有序序列
* 线性表的的基本操作
 1. func MakeEmpty(maxlen int) List :初始化一个线性表
 2. func (this *List) FindE(K int) ElementType :根据位序K,返回响应元素
 3. func (this *List) FindFristEleIndex(ele ElementType) int:在线性表L中查找E的第一次出现的位置
 4. func (this *List) Insert(ele ElementType, i int) :在位序I前插入一个新元素E
 5. func (this *List) Delete(i int) :删除指定位序I的元素
 6. func (this *List) Length() int: 返回线性表L的长度  

package main

import (
	"errors"
	"time"
)

/**
线性表的的数据单元 数据类型可以随便定义  当然可以是一些简单的基本数据类型 例如 int float string
以下是例子 我将存储一些人员信息
*/
type ElementType struct {
	Brithday time.Time //生日  golang 自带的time包中的一个结构体
	Name     string    //姓名
	IDNumber string    //身份证号
	Sex      bool      //性别
}

type List struct {
	MaxLen     int           //最大长度
	CurrentLen int           //当前长度
	Man        []ElementType //数据单元为ElementType的切片  在golang中 切片与数组的底层就是一个线性表
}

//初始化一个线性表
func MakeEmpty(maxlen int) List {
	return List{MaxLen: maxlen, CurrentLen: 0, Man: make([]ElementType, maxlen)}
}

//返回线性表中序号为K的元素
func (this *List) Find(K int) ElementType {
	return this.Man[K]
}

//在线性表L中查找E的第一次出现的位置
func (this *List) FindFristEleIndex(ele ElementType) int {
	for index, val := range this.Man {
		if val == ele {
			return index
		}
	}
	return -1
}

//在位序I前插入一个新元素E
func (this *List) Insert(ele ElementType, i int) error {
	if this.CurrentLen == this.MaxLen {
		return errors.New("满了")
	}
	if i < 0 || i > this.MaxLen {
		return errors.New("请检查i值")
	}
	for j := this.CurrentLen - 1; j >= i; j-- {
		this.Man[j+1] = this.Man[j]
	}
	this.CurrentLen++
	this.Man[i] = ele

	return nil
}

//删除指定位序I的元素
func (this *List) Delete(i int) error {
	if i >= this.CurrentLen {
		return errors.New("请检查 i 值")
	}
	for j := i; j < this.CurrentLen-1; j++ {
		this.Man[j] = this.Man[j+1]
	}
	this.Man[this.CurrentLen-1] = ElementType{}
	this.CurrentLen--
	return nil
}

func (this *List) Length() int {
	return this.CurrentLen
}

func main() {

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值