英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论