速戰速決 go - go 容器: 列表(列表的增刪改查和遍歷)

速戰速決 go https://github.com/webabcd/GoSample
作者 webabcd

速戰速決 go - go 容器: 列表(列表的增刪改查和遍歷)

示例如下:

container/list.go

// go 容器 - 列表(列表的增刪改查和遍歷)
// 注:
// 1、List 中可以包含不同類型的數據
// 2、添加進 List 中的數據都會被封裝爲 Element 對象
// 3、通過 Element.Value 獲取或修改元素的值

package container

import (
	"container/list"
	"fmt"
)

func ListSample() {
	list_sample1()
	list_sample2()
}

func list_sample1() {
	// 聲明一個 List(此處的 a 是一個指針)
	a := list.New()
	// 聲明一個 List(此處的 b 是指針指向的值)
	var b list.List
	fmt.Printf("%p, %p\n", a, &b) // 0xc000110480, 0xc0001104b0

	// 在尾部添加一個數據
	// a 是指針,這裏不是應該寫成 (*a).PushBack("a") 嗎?當然可以這麼寫,不過由於 go 支持語法糖(syntactic sugar)技術,他會自動轉換的,所以你也可以按如下方式寫
	a.PushBack("a") // a
	// 在開頭添加一個數據
	a.PushFront(0) // 0 a
	// 在尾部添加一個 List
	a.PushBackList(a) // 0 a 0 a

	b.PushBack(true)
	// 在開頭添加一個 List
	a.PushFrontList(&b) // true 0 a 0 a

	// 返回值就是你添加數據對應的 Element 對象
	el := a.PushBack("x") // true 0 a 0 a x
	// 在指定的 Element 對象之後添加數據
	a.InsertAfter("x_after", el) // true 0 a 0 a x x_after
	// 在指定的 Element 對象之前添加數據
	a.InsertBefore("x_before", el) // true 0 a 0 a x_before x x_after

	// 刪除指定的 Element 對象
	a.Remove(el) // true 0 a 0 a x_before x_after

	// 遍歷 List
	for i := a.Front(); i != nil; i = i.Next() {
		fmt.Println(i.Value)
	}
}

func list_sample2() {
	a := list.New()
	a.PushBack(0)
	a.PushBack(1)
	a.PushBack(2)
	a.PushBack(3)
	a.PushBack(4)
	a.PushBack(5)

	// List 有如下方法
	//   Font() - 取第一個數據的 Element 對象
	//   Back() - 取最後一個數據的 Element 對象
	//   MoveToFront(), MoveToBack(), MoveBefore(), MoveAfter() - 移動 Element 對象的相關操作
	// Element 有如下方法和屬性
	//   Next() - 獲取當前 Element 對象的在 List 中的下一個 Element 對象(沒有則會返回 nil)
	//   Prev() - 獲取當前 Element 對象的在 List 中的上一個 Element 對象(沒有則會返回 nil)
	//   Value - 表示 Element 對象的值
	b := a.Front().Next()        // 1
	c := a.Front().Next().Next() // 2
	// 將 c 移動到 List 的開頭
	a.MoveToFront(c) // 2 0 1 3 4 5
	// 將 b 移動到 c 的後面
	a.MoveAfter(b, c) // 2 1 0 3 4 5

	// 修改指定 Element 對象的值
	a.Back().Value = 100 // // 2 1 0 3 4 5

	// 取指定 Element 對象的值
	fmt.Println(b.Value, c.Value) // 1 2

	// 遍歷 List
	for i := a.Front(); i != nil; i = i.Next() {
		fmt.Println(i.Value)
	}
}

速戰速決 go https://github.com/webabcd/GoSample
作者 webabcd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章