泛型循环链表

package main

import "fmt"

type Node[T any] struct {
    data T
    next *Node[T]
}

type CircularLinkedList[T any] struct {
    head *Node[T]
    tail *Node[T]
    size int
}

func (list *CircularLinkedList[T]) Append(data T) {
    node := &Node[T]{data: data}
    if list.size == 0 {
        list.head = node
        list.tail = node
        node.next = list.head
    } else {
        list.tail.next = node
        list.tail = node
        list.tail.next = list.head
    }
    list.size++
}

func (list *CircularLinkedList[T]) Print() {
    if list.size == 0 {
        fmt.Println("empty list")
        return
    }
    current := list.head
    for i := 0; i < list.size; i++ {
        fmt.Printf("%v ", current.data)
        current = current.next
    }
    fmt.Println()
}

func main() {
    list := &CircularLinkedList[string]{}
    list.Append("123")
    list.Append("123")
    list.Append("123")
    list.Append("123")
    list.Print()
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
goStruct
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!