2

In an attempt to understand recursion better, I've decided to try a recursive function to find an item in a linked list instead of a while loop.

Near the end, my recursive function seems to be doing the right thing by returning the correct node, but then it runs return a few more times unexpectedly (I don't know why) and returns an incorrect object. Am I missing something?

var linkedList = {
  element: 'head',
  next: {
    element: 'SF',
    next: {
      element: 'LA',
      next: {
        element: 'SD',
        next: {
          element: 'NY',
          next: null
        }
      }
    }
  }
}


function getItem(city, list) {
  var item = list

  if (item.element != city) {
    item = item.next
    getItem(city, item)
  }

  return item
}

console.log( getItem('SD', linkedList ) ) // logs "SF" node but I expect "SD" node

3 Answers 3

7

Your function should be like this:

function getItem(city, item) {
  if(item === null)
    return null;
  if (item.element === city)
    return item;
  return getItem(city, item.next)
}

This is the general pattern:

find-recursively (predicate, element)

    // terminal condition, failure
    if element is null 
        return null

    // ok, found it
    if element matches predicate
        return element

    // recurse deeper
    return find-recursively (predicate, element.next)
Sign up to request clarification or add additional context in comments.

Comments

3

You should catch the return value of the recursive function inside the if.

Just do

if (item.element != city) {
    item = item.next
    item = getItem(city, item)
}

And it works as expected.

2 Comments

Sorry, could you explain what catching the return value inside the if does? I'm still not understanding the bug. Is it the same as returning something inside the if? But it works!
getItem returns each time the current element, however, in your current code you omit that and thus you return list again.
2

The point is that you are creating the "item" variable inside the iteration. When you go to the next call you lost the value of the parent process because eu are registering it again, so you have to create it outside the function and use the reference inside. Look:

// Creating the variable
var item = null;

function getItem(city, list) {
  // Working with the value
  item = list;

  if (item.element != city) {
    item = item.next
    getItem(city, item)
  }
  return item
}

console.log( getItem('SD', linkedList ) ) // logs "SF" node but I expect "SD" node

// My log returns "SD"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.