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

huangapple go评论76阅读模式
英文:

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

问题

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

type Node struct {
  data int
  next *Node
}

我尝试了这样的方法,但总是返回1。

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

I have a single linked list. how do I get the length of the linked list with a recursive method that had a pointer receiver?

type Node struct {
  data int
  next *Node
}

I had tried like this, but always return 1

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

答案1

得分: 1

你的解决方案不是递归的。它有编译错误。但是如果我们想要修复它,可以像这样修改:

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())
}

但是这种写法不是一个好主意,更好的做法是将其改为一个接受 Node 并返回其长度的函数:

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))
}
英文:

Your solution is not recursive. It's have compilation error. But if we want to fix it it could be like this:

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())
}

But this is not a good idea to write length method, It's better to change it to a function that accepts a Node and returns its length:

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))
}

huangapple
  • 本文由 发表于 2022年1月20日 23:16:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/70788754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定