Golang數據結構算法之數組相關
提供的接口
- 返回數組大小
- 根據索引獲取數組元素
- 根據索引修改數組元素
- 根據索引插入數組元素
- 數組末尾追加元素(添加元素)
- 清空數組
- 根據索引刪除數組元素
- 返回數組字符串
首先定義一個數組結構體,結構體內容爲數組內容以及數組大小,如下
type ArrayList struct {
dataStore [] interface{} // 數組的存儲
TheSize int // 數組的大小
}
數組類型採用interface{}形式表示可以接收任何類型的數組,例如字符串和整型
編寫數組初始化方法
func NewArrayList() *ArrayList {
list := new(ArrayList) // 初始化結構體
list.dataStore = make([]interface{},0,10) //開闢內存
list.TheSize = 0
return list
}
添加數組元素(追加數組)Append(),調用默認庫的append方法,記得同步增加長度
func (list *ArrayList)Append(newval interface{}) {
list.dataStore = append(list.dataStore,newval)
list.TheSize++
}
根據索引獲取數組元素
func (list *ArrayList) Get(index int) (interface{},error){
if index < 0 || index >= list.TheSize {
return nil,errors.New("索引越界")
}
return list.dataStore[index],nil
}
根據索引修改數組元素
func (list *ArrayList)Set(index int, newval interface{}) error{
if index < 0 || index >= list.TheSize {
return errors.New("索引越界")
}
list.dataStore[index] = newval // 對數據進行新值設置
return nil
}
根據索引插入數組元素
func (list *ArrayList)Insert(index int, newval interface{}) error{
if index < 0 || index >= list.TheSize {
return errors.New("索引越界")
}
list.checkisFull() // 檢測數組是否爲滿,是否需要開闢雙倍內存
list.dataStore = list.dataStore[:list.TheSize+1] // 插入數據,內存移動一位
for i := list.TheSize;i > index;i--{
list.dataStore[i] = list.dataStore[i-1]
}
list.dataStore[index] = newval
list.TheSize++
return nil
}
插入方法有一個檢測數組是否爲滿的方法,如果數組已經是滿的時無法進行元素插入操作的,因爲開闢內存時,默認數組10位,如果數組爲滿的話,開啓雙倍內存,以插入新元素,checkisFull()如下
func (list *ArrayList)checkisFull () {
if list.TheSize == cap(list.dataStore) {
newdataStore := make([]interface{},2*list.TheSize,2*list.TheSize) // 開闢雙倍內存
copy(newdataStore,list.dataStore) // 拷貝數據
list.dataStore = newdataStore
}
}
清空數組
func (list *ArrayList)Clear(){
list.dataStore = make([]interface{},0,10)
list.TheSize = 0
}
根據索引刪除數組元素
func (list *ArrayList)Delete(index int) error{
if index < 0 || index >= list.TheSize {
return errors.New("索引越界")
}
list.dataStore = append(list.dataStore[:index],list.dataStore[index+1:]...)
return nil
}
這裏巧用了append方法,將要刪除元素索引位置之前和之後的元素進行了拼接,返回的就是刪除索引元素後的新數組
測試如下
func main() {
var list ArrayList.List = ArrayList.NewArrayList()
list.Append("a1")
list.Append("b")
list.Append("c")
for i := 0; i < 10; i++ {
list.Insert(1, "x")
fmt.Println(list)
}
}
輸出如下
[a x b c]
[a x x b c]
[a x x x b c]
[a x x x x b c]
[a x x x x x b c]
[a x x x x x x b c]
[a x x x x x x x b c]
[a x x x x x x x x b c]
[a x x x x x x x x x b c]
[a x x x x x x x x x x b c]
Process finished with exit code 0
可見是開闢了雙倍內存後的插入