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