线性表
1、全名线性存储结构
2、数据元素之间存在一对一的线性关系。
3、分为顺序存储结构(简称顺序表)和链式存储结构(简称链表)。
顺序表实现部分
顺序表:将数据依次存储在的整块物理空间中
顺序表结构图.png
type SeqList struct {
SeqListData []interface{}
Length int //记录当前顺序表的长度
Size int //记录分配时的存储容量
}
//初始化顺序表
func NewSeqList() *SeqList {
return &SeqList{
SeqListData: make([]interface{}, 0, 20),
Length: 0,
Size: 20,
}
}
//判断顺序表是否已经满了
func (s *SeqList)IsFull() bool {
if s.Length == s.Size{
return true
}
return false
}
//追加
func (s *SeqList)Append(e interface{}) bool {
if s.IsFull(){
return false
}
s.SeqListData = append(s.SeqListData, e)
s.Length++
return true
}
//插入
func (s *SeqList)Insert(e interface{}, i int) bool {
if s.IsFull(){ //顺序表已经满了
return false
}
if s.Length < i || i < 0{ //越界了
return false
}
s.SeqListData = append(s.SeqListData, "")
s.Length++
for j:=s.Length;j>i;j--{
s.SeqListData[j] = s.SeqListData[j-1]
}
s.SeqListData[i] = e
return true
}
//删除
func (s *SeqList)DeleteWithIndex(i int) bool {
if i < 0 || s.Length <= i{
return false
}
for j := i;j<s.Length-1;j++{
s.SeqListData[j] = s.SeqListData[j+1]
}
s.SeqListData = s.SeqListData[:s.Length-1]
s.Length--
return true
}
//查找
func (s *SeqList)GetDataWithIndex(i int) (bool, interface{}) {
if s.Length <= i || i < 0{ //允许从第0个元素查找
return false, nil
}
return true, s.SeqListData[i]
}
func (s *SeqList)GetDataWithElement(e interface{}) (bool, int) {
if s.Length < 1{
return false, -1
}
for i, j := range s.SeqListData{
if j == e{
return true, i
}
}
return false, -1
}