在leetcode上刷题,遇到了很多关于链表的问题,今天就回顾一下,go语言中关于单链表的实现,主要是链表的创建,添加,插入,删除,获取,话不多说,上代码:
package main import "fmt" type Node struct { //定义结点 data int //节点的值 next *Node //后继结点 } type List struct { //定义一个链表 size uint //链表中元素的个数 head *Node //头结点 tail *Node //尾结点 } func (list *List) init (){ //链表初始化 (*list).size=0 (*list).head=nil (*list).tail=nil } func (list *List) Append (i int) bool{ //在链表尾部添加一个元素 node := &Node{data: i} if (*list).size == 0{ //链表为空,此时添加的为头结点 (*list).head=node }else{ oldtail :=(*list).tail //得到尾结点,添加 (*oldtail).next = node } (*list).tail=node //调整尾结点 (*list).size++ return true } func (list *List) Insert (i uint,n int) bool{ //向指定位置插入一个值 node := &Node{data: n} if node == nil || i>(*list).size || (*list).size == 0{ return false } if i==0{ (*node).next=(*list).head (*list).head=node }else{ preItem :=(*list).head for j :=1;j<int(i);j++{ preItem = (*preItem).next } (*node).next=(*preItem).next (*preItem).next=node } (*list).size++ return true } func (list *List) Delete (i uint) bool{ //删除指定位置的结点 if i>(*list).size { return false } if i==0{ (*list).head=(*list).head.next if (*list).size==1{ (*list).tail=nil } }else{ preItem :=(*list).head for j :=1;j<int(i);j++{ preItem = (*preItem).next } (*preItem).next=(*preItem).next.next if i == (*list).size-1 { (*list).tail=preItem } } (*list).size-- return true } func (list *List) Get (i uint) *Node{ //获取指定位置的结点 if i >(*list).size{ return nil } node :=(*list).head for j:=0;j>int(i);j++{ node=(*node).next } return node } func main(){ list := List{} fmt.Println(list.Append(1)) //添加一个头结点 1 fmt.Println(list.head.data) list.Insert(1,2) //在头节点后插入一个 2 fmt.Println(list.size) list.Delete(0) //删除头结点 fmt.Println(list.head.data) println(list.Get(0).data) //获取此时的头结点 }
结果:
D:\gowork\src\learn\12\1>go run list.go
true
1
2
2
2