如何使用方法指针的递归获取golang中链表的长度?

how to get length of linked list in golang with recursive of method pointer?

我有一个链表。如何使用具有指针接收器的递归方法获取链表的长度?

type Node struct {
  data int
  next *Node
}

我试过这样,但总是return1

func (n *Node) recursiveLength() (result int) {
  if n != nil {
    result += 1
    n = n.next
  }
  return
}

您的解决方案不是递归的。它有编译错误。但是如果我们想修复它可能是这样的:

package main

import "fmt"

type Node struct {
    data int
    next *Node
}

func (n *Node) recursiveLength() (result int) {
    if n != nil {
        result += 1
        n = n.next
        return result + n.recursiveLength()
    }
    return 0
}

func main() {
    x := Node{data: 0, next: &Node{data: 1, next: &Node{data: 2, next: nil}}}
    fmt.Println(x.recursiveLength())
}

但这不是写长度方法的好主意,最好将其更改为接受节点和 returns 其长度的函数:

package main

import "fmt"

type Node struct {
    data int
    next *Node
}

func recursiveLength(n *Node) (result int) {
    if n != nil {
        n = n.next
        return 1 + recursiveLength(n)
    }
    return 0
}

func main() {
    x := Node{data: 0, next: &Node{data: 1, next: &Node{data: 2, next: nil}}}
    fmt.Println(recursiveLength(&x))
}