Golang container包下list(数据结构中的链表)的使用

import "container/list"

list包实现了双向链表。要遍历一个链表:

for e := l.Front(); e != nil; e = e.Next() {
	// do something with e.Value
}

链表的基础知识以及原始操作详见:https://blog.csdn.net/weixin_42117918/article/details/81838498

本文主要讨论如何使用golang提供的包快速使用链表。

package main

import (
	"container/list"
	"fmt"
)
func main() {
	l:=list.New()
	l.Init()
	l.PushBack(0) //添加数据(链表尾部添加)
	l.PushBack(1)
	e2:=l.PushFront(2) //添加到链表的头部
	l.PushFront(3)
	//遍历
	for e:=l.Front();e!=nil;e=e.Next(){
		fmt.Println(e.Value)
	}
	fmt.Println("==============添加数据===========")
	l.InsertAfter(333,e2)  //在e2指针所在位置的后面添加
	l.InsertBefore(666,e2)//在e2指针所在位置的前面添加
	for e:=l.Front();e!=nil;e=e.Next(){
		fmt.Println(e.Value)
	}
	fmt.Println("=============删除数据===========")
	l.Remove(e2) //删除指针e2指向的位置
	for e:=l.Front();e!=nil;e=e.Next(){
		fmt.Println(e.Value)
	}
	fmt.Println("=============链表的拼接===========")
	r:=list.New()
	r.Init()
	r.PushBack(888)
	r.PushBack(123)
    l.PushBackList(r) //添加到链表l的末尾
	for e:=l.Front();e!=nil;e=e.Next(){
		fmt.Println(e.Value)
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42117918/article/details/90737895