Go list 应用解析与实例

list 概述

  • list 是一种非连续存储的容器,由多个节点组成,节点通过一些变量记录彼此直接的关系。
  • Go 语言中list的实现原理是双向链表,list能高兴地进行任意位置元素的插入和删除操作。

Golang的 list 内置库

Golang 的标准库提供高级的数据结构List,具体位置在 container/list/list.go 文件中。

  • container/list 包里注意有两个数据结构类型: ‘Element’ & ‘List’;
  • Element 类型代表双向链表, 相当于 C++ 里的 “iterator”;
  • List 代表一个双向链表,list 零值为一个空的、可用的链表;
  • Element 有 Prev 和 Next 方法用于获取上一个、下一个 element 元素,element 可用直接调用value属性。

Element & List 方法集

1、 type Element

  • func (e *Element) Next() *Element
  • func (3 *Element) Prev() *Element

2、 type List

  • func New() *List
  • func (l *List) Init() *List
  • func (l *List) Len() int
  • func (l *List) Front() || Back() *Element //描述 front 与Back 方法
  • func (l *List) PushFront(v interface{}) || PushBack(v interface{}) *Element
  • func (l *List) PushFrontList(other *List) || PushBackList(other *List) *Element
  • func (l *List) InsertBefore(v interface{},mark *Element) || InsertAfter(v interface{},mark *Element) *Element
  • func (l *List) MoveToFront(e *Element) || MoveToBack(e *Element)
  • func (l *List) MoveBefore(e,mark *Element) ||MoveAfter(e,mark *Element)
  • func (l *List) Remove(e *Element) interface{}

list 声明

lis := list.New()
var lis list.List

在 C++ 里面,list的成员必须是同一个类型数据,而Go语言中却可用插入任意类型的成员。

lsit 遍历

for e := lis.Front; e != nil; e = e.Next() {
    
    
	fmt.Println(e.Value)
}

for n := lis.Back(); n != nil; n = n.Prev() {
    
    
	fmt.Println(n.Value)
}

实例 1


package main

import (
        "fmt"
        "container/list"
)

func main() {
    
    
        copyList()
}


func printListInfo(info string, lis *list.List) {
    
    
        fmt.Println(info + "-------")
        fmt.Printf("%T : %v \t, length: %d \n",lis,lis,lis.Len())
        fmt.Printf("\n\r")
}

func iteraterList(lis *list.List) {
    
    
        i := 0
        for e := lis.Front(); e != nil; e = e.Next() {
    
    
                i++
                fmt.Printf(" %d : %v \t", i, e.Value)
        }
        fmt.Println("\n\r","--------end-------")
}

func copyList() {
    
    
        list1 := list.New()
        
        printListInfo("declare:",list1)
        list1.PushBack("one")
        list1.PushBack("2")
        list1.PushFront("first")
        list1.PushBack("three")
        
        printListInfo("declare1: ",list1)
        iteraterList(list1)
}

运行效果如下:

robot@ubuntu:~/gomod/src/list$ go run elist.go 
declare:-------
*list.List : &{
    
    {
    
    0xc00005e150 0xc00005e150 <nil> <nil>} 0} 	, length: 0 

declare1: -------
*list.List : &{
    
    {
    
    0xc00005e210 0xc00005e240 <nil> <nil>} 4} 	, length: 4 

 1 : first 	 2 : one 	 3 : 2 	 4 : three 	
 --------end-------

猜你喜欢

转载自blog.csdn.net/weixin_38387929/article/details/119611863