单向循环链表

双向循环链表

package mainimport "fmt"type Node struct { Value int Next *Node}type List struct{ Size uint Head *Node // 首节点}//初始化func NewList() *List{ return &List{ Size:0, Head:nil, }}func (this *List) Add(value int){ node := &Node{Value:value} if this.Size == 0{ //新增node的next指向自己 //头节点更新为新增的node node.Next,this.Head= node,node }else { //新增node的next指向头节点 node.Next= this.Head // 找到尾节点,将尾节点的next指向新增的节点 // 尾节点的next指向当前的头节点 tail := this.Head for tail.Next != this.Head{tail = tail.Next} tail.Next = node //头节点更新为当前新增的node this.Head = node } this.Size++}func (this *List) ForEach(){ current := this.Head for { fmt.Println(current.Value) // 尾部的next是指向头部的 if current.Next == this.Head{ break } current = current.Next }}func main() { list := NewList() list.Add(1) list.Add(2) list.Add(3) list.ForEach() fmt.Println("-------------------") list.Add(0) list.ForEach()}