go语言实现循环单链表
时间: 2024-04-24 13:03:43 浏览: 18
以下是使用Go语言实现循环单链表的示例代码:
```go
package main
import (
"fmt"
)
type Node struct {
data interface{}
next *Node
}
type CircularLinkedList struct {
head *Node
tail *Node
size int
}
func (list *CircularLinkedList) getSize() int {
return list.size
}
func (list *CircularLinkedList) isEmpty() bool {
return list.head == nil
}
func (list *CircularLinkedList) addFirst(data interface{}) {
newNode := &Node{data, nil}
if list.isEmpty() {
list.head = newNode
list.tail = newNode
newNode.next = newNode
} else {
newNode.next = list.head
list.head = newNode
list.tail.next = newNode
}
list.size++
}
func (list *CircularLinkedList) addLast(data interface{}) {
newNode := &Node{data, nil}
if list.isEmpty() {
list.head = newNode
list.tail = newNode
newNode.next = newNode
} else {
newNode.next = list.head
list.tail.next = newNode
list.tail = newNode
}
list.size++
}
func (list *CircularLinkedList) removeFirst() interface{} {
if list.isEmpty() {
return nil
}
data := list.head.data
list.head = list.head.next
list.tail.next = list.head
list.size--
if list.isEmpty() {
list.tail = nil
}
return data
}
func (list *CircularLinkedList) display() {
if list.isEmpty() {
fmt.Println("List is empty")
return
}
fmt.Println("List:")
currentNode := list.head
for {
fmt.Printf("%v -> ", currentNode.data)
currentNode = currentNode.next
if currentNode == list.head {
break
}
}
fmt.Println()
}
func main() {
list := &CircularLinkedList{}
list.addFirst(1)
list.addLast(2)
list.addLast(3)
list.addFirst(0)
list.display()
fmt.Println("Size:", list.getSize())
list.removeFirst()
list.removeFirst()
list.display()
fmt.Println("Size:", list.getSize())
}
```
输出结果:
```
List:
0 -> 1 -> 2 -> 3 ->
Size: 4
List:
2 -> 3 ->
Size: 2
```
该代码实现了循环单链表的基本功能,包括添加节点、删除节点、获取链表大小和显示链表内容等。在该示例中,循环单链表的头节点和尾节点都是存储在链表对象中的,而不是每个节点中都保存头节点和尾节点的指针。同时,该示例还实现了判断链表是否为空的方法。