ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Go list的介绍与使用

2022-05-20 11:04:54  阅读:189  来源: 互联网

标签:mylist 元素 list 介绍 mark Go Element any


介绍

Go的list是一个双向链表,链表可以高效的删除插入元素,很多场景是需要用到这个结构的,比如cache

使用

list在包container/list下,可以通过NeW()初始化或者var声明
两种方法如下

mylist := list.New()
var mylist list.List
  • 常用的函数以及功能如下表格
    | 函数|功能 |
    | :------------ | :------------ |
    | PushFront(v any) *Element |在最前插入元素 |
    | PushBack(v any) *Element |在最后插入元素 |
    | InsertBefore(v any, mark *Element) *Element |将元素插到mark前 |
    | InsertAfter(v any, mark *Element) *Element |将元素插到mark后 |
    |MoveToFront(e *Element)|将指定元素移到最前|
    |MoveToBack(e *Element)|将指定元素移到最后|
    |MoveBefore(e, mark *Element)|将指定元素移到mark前|
    |MoveAfter(e, mark *Element)|将指定元素移到mark后|
    |PushBackList(other *List)|将另一个list插入到当前list后 |
    |PushFrontList(other *List)|将另一个list插入到当前list前|
    |Remove(e *Element) any|删除指定元素|

  • demo

package main

import (
	"container/list"
	"fmt"
)

func main() {
	mylist := list.New()
	one := mylist.PushFront("first")
	two := mylist.PushBack("second")
	head := mylist.InsertAfter("third", one)
	three := mylist.InsertAfter(4, two)
	mylist.Remove(three)
	mylist.MoveToFront(head)
	for e := mylist.Front(); e != nil; e = e.Next() {
		fmt.Printf("%v ", e.Value)//third first second 
	}
}

标签:mylist,元素,list,介绍,mark,Go,Element,any
来源: https://www.cnblogs.com/notomatoes/p/16291543.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有