[数据结构]之顺序表
描述
顺序表:是指在一段连续的存储单元存储数据的线性表。多使用数组来实现。
数据结构
1 属性:
最大长度 CAP
当前长度 Length
存储数组 Elements
2 操作:
Get(index) 获取元素
Insert(index,elem) 插入元素
Delete(index) 删除第index个元素
## 实现
使用go语言实现代码如下:
package mainimport ("fmt")const CAP = 20type SqList struct {elemets [CAP]stringlength int}/** 获取顺序表的第index元素*/func (list *SqList) Get(index int) (string, error) {if list.length == 0 || index < 0 || index > list.length-1 {return "", fmt.Errorf("the index %d Out Of Bounds", index)}return list.elemets[index], nil}/** 插入顺序表元素,在第index位置*/func (list *SqList) Insert(index int, elem string) error {if list.length == CAP {return fmt.Errorf("the list is full")}if index < 0 || index > list.length {return fmt.Errorf("the index %d Out Of Bounds", index)}//如果不是在最后插入,需要移动后面的元素if index < list.length {for i := list.length - 1; i >= index; i-- {list.elemets[i+1] = list.elemets[i]}}list.elemets[index] = elemlist.length++return nil}/** 删除顺序表元素,在第index位置*/func (list *SqList) Delete(index int) error {if list.length == 0 {return fmt.Errorf("the list is empty")}if index < 0 || index > list.length {return fmt.Errorf("the index %d Out Of Bounds", index)}//如果不是在最后删除,需要移动后面的元素if index < list.length {for i := index; i < list.length; i++ {list.elemets[i] = list.elemets[i+1]}}list.length--return nil}func main() {list := &SqList{}list.Insert(0, "AAAAA")list.Insert(1, "BBBBB")list.Insert(2, "CCCCC")list.Delete(1)for i := 0; i < list.length; i++ {elem, _ := list.Get(i)fmt.Printf("get elem %d value:%v\n", i, elem)}}