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

Issue

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
}

Solution

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

Answered By – S4eed3sm

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.