单向循环链表

image.png

双向循环链表

image.png

  1. package main
  2. import "fmt"
  3. type Node struct {
  4. Value int
  5. Next *Node
  6. }
  7. type List struct{
  8. Size uint
  9. Head *Node // 首节点
  10. }
  11. //初始化
  12. func NewList() *List{
  13. return &List{
  14. Size:0,
  15. Head:nil,
  16. }
  17. }
  18. func (this *List) Add(value int){
  19. node := &Node{Value:value}
  20. if this.Size == 0{
  21. //新增node的next指向自己
  22. //头节点更新为新增的node
  23. node.Next,this.Head= node,node
  24. }else {
  25. //新增node的next指向头节点
  26. node.Next= this.Head
  27. // 找到尾节点,将尾节点的next指向新增的节点
  28. // 尾节点的next指向当前的头节点
  29. tail := this.Head
  30. for tail.Next != this.Head{tail = tail.Next}
  31. tail.Next = node
  32. //头节点更新为当前新增的node
  33. this.Head = node
  34. }
  35. this.Size++
  36. }
  37. func (this *List) ForEach(){
  38. current := this.Head
  39. for {
  40. fmt.Println(current.Value)
  41. // 尾部的next是指向头部的
  42. if current.Next == this.Head{
  43. break
  44. }
  45. current = current.Next
  46. }
  47. }
  48. func main() {
  49. list := NewList()
  50. list.Add(1)
  51. list.Add(2)
  52. list.Add(3)
  53. list.ForEach()
  54. fmt.Println("-------------------")
  55. list.Add(0)
  56. list.ForEach()
  57. }