golang 实现数据结构-顺序表

顺序表

package main

import (
	"errors"
	"fmt"
)

// 逻辑结构: 线性表(具有相同数据元素是有限序列)

type SequenceList struct {
	data             *[]interface{}
	length, capacity int
}

//初始化表
func (s *SequenceList) InitList(InitListSize int) {
	data := make([]interface{}, InitListSize)
	s.data = &data
	s.length = 0
	s.capacity = InitListSize
}

//求表长
func (s SequenceList) GetListLength() int {
	return s.length
}

// 判空
func (s SequenceList) isNull() bool {
	if s.length != 0 {
		return false
	}
	return true
}

// 判满

func (s SequenceList) isFull() bool {
	if s.length >= s.capacity {
		return true
	}
	return false
}

// 按位插入操作

func (s *SequenceList) ListInsert(index int, Element interface{}) error {
	if index < 1 || index > s.length+1 || s.isFull() {
		return errors.New("illegal index")
	}
	for i := s.length; i >= index; i-- {
		(*s.data)[i+1] = (*s.data)[i]
	}
	(*s.data)[index-1] = Element
	s.length++
	return nil
}

// 按值查找(查找第一个元素值等于 e 的元素, 并返回其位序)

func (s SequenceList) FindEleByValue(Ele interface{}) interface{} {
	for i := 0; i < s.length; i++ {
		if (*s.data)[i] == Ele {
			return i + 1
		}
	}
	return nil
}

// 按位查找
func (s SequenceList) FindEleByIndex(index int) (interface{}, error) {
	if index > s.length || index < 1 {
		return nil, errors.New("illegal index")
	}
	return (*s.data)[index-1], nil
}

// 删除操作(删除表中第 i 个元素, 并返回 e)

func (s *SequenceList) ListDelete(index int) (interface{}, error) {
	if index > s.length || index < 1 {
		return nil, errors.New("illegal index")
	}
	e := (*s.data)[index-1]
	for i := index; i < s.length; i++ {
		(*s.data)[i-1] = (*s.data)[i]
		if i + 1 >= s.length{
			(*s.data)[i] = nil
		}
	}
	s.length--
	return e, nil
}

// PrintList 输出
func (s SequenceList) PrintList() {
	fmt.Printf("List Show[data:%v, length:%v, capacity:%v]\n", *s.data, s.length, s.capacity)
}

// DestroyList 销毁
func (s *SequenceList) DestroyList() {
	s.data = nil
	s.length = 0
	s.capacity = 0
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值