Golang 实现循环链表
在这篇文章中,我们将学习如何使用结构体和切片方法编写一个Go语言程序来实现循环链表。循环链表是这样创建的,链表的每个节点都指向下一个节点,而最后一个节点再次指向起始节点。
示例1
在这个示例中,我们将编写一个Go语言程序,使用结构体来存储链表的每个节点,以实现循环链表。
package main
import "fmt"
type Node struct {
   data int
   next *Node
}
type CircularLinkedList struct {
   head *Node
   tail *Node
}
func NewCircularLinkedList() *CircularLinkedList {
   return &CircularLinkedList{head: nil, tail: nil}
}
func (cll *CircularLinkedList) IsEmpty() bool {
   return cll.head == nil
}
func (cll *CircularLinkedList) AddNode(data int) {
   newNode := &Node{data: data, next: nil}
   if cll.IsEmpty() {
      cll.head = newNode
      cll.tail = newNode
      newNode.next = cll.head
   } else {
      cll.tail.next = newNode
      cll.tail = newNode
      newNode.next = cll.head
   }
}
func (cll *CircularLinkedList) Traverse() {
   if cll.IsEmpty() {
      fmt.Println("Circular Linked List is empty")
   } else {
      current := cll.head
      for {
         fmt.Printf("%d -> ", current.data)
         current = current.next
         if current == cll.head {
            break
         }
      }
      fmt.Printf("%d\n", cll.head.data)
   }
}
func main() {
   cll := NewCircularLinkedList()
   fmt.Println("The nodes of circular linked list are:")
   cll.AddNode(1)
   cll.AddNode(2)
   cll.AddNode(3)
   cll.AddNode(4)
   cll.AddNode(5)
   cll.Traverse()
}
输出
The nodes of circular linked list are:
1 -> 2 -> 3 -> 4 -> 5 -> 1
示例2
在这个示例中,我们将编写一个Go语言程序,通过使用切片来实现循环链表并存储值到列表中。
package main
import (
   "fmt"
)
type CircularLinkedList struct {
   values []int
   size   int
}
func (cll *CircularLinkedList) AddNode(value int) {
   cll.values = append(cll.values, value)
   cll.size++
}
func (cll *CircularLinkedList) RemoveNode(value int) bool {
   for i, v := range cll.values {
      if v == value {
         cll.values = append(cll.values[:i], cll.values[i+1:]...)
         cll.size--
         return true
      }
   }
   return false
}
func (cll *CircularLinkedList) PrintList() {
   for i := 0; i < cll.size; i++ {
      fmt.Printf("%d -> ", cll.values[i%cll.size])
   }
   fmt.Printf("%d", cll.values[0])
   fmt.Println()
}
func main() {
   cll := &CircularLinkedList{[]int{}, 0}
   // add nodes
   cll.AddNode(1)
   cll.AddNode(2)
   cll.AddNode(3)
   cll.AddNode(4)
   fmt.Println("The obtained circular linked list is:")
   cll.PrintList()
   cll.RemoveNode(3)
   fmt.Println()
   fmt.Println("The circular linked list obtained after removing node 3 are:")
   cll.PrintList()
}
输出
The obtained circular linked list is:
1 -> 2 -> 3 -> 4 -> 1
The circular linked list obtained after removing node 3 are:
1 -> 2 -> 4 -> 1
结论
我们成功编译并执行了一个go语言程序,用于实现循环链表,并附上了示例。这里我们使用了两个程序。在第一个程序中,我们使用一个结构体来存储列表中节点的值和位置,而在第二个程序中,我们使用了一个切片来存储数据。
极客笔记