【问题标题】:JavaScript: Recursive function used to find a Linked list node returns wrong nodeJavaScript:用于查找链表节点的递归函数返回错误节点
【发布时间】:2016-05-15 10:32:33
【问题描述】:

为了更好地理解递归,我决定尝试使用递归函数在链表中查找项目,而不是 while 循环。

接近尾声,我的递归函数似乎通过返回正确的节点来做正确的事情,但随后它意外地运行 return 几次(我不知道为什么)并返回一个不正确的对象。我错过了什么吗?

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

【问题讨论】:

    标签: javascript function recursion linked-list


    【解决方案1】:

    你的函数应该是这样的:

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

    这是一般模式:

    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)
    

    【讨论】:

      【解决方案2】:

      你应该在 if 中捕获递归函数的返回值。

      做事

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

      它按预期工作。

      【讨论】:

      • 抱歉,您能解释一下在if 中捕获返回值的作用吗?我仍然不明白这个错误。是否与在if 中返回内容相同?但它有效!
      • getItem 每次返回当前元素,但是,在您当前的代码中,您省略了它,因此您再次返回 list
      【解决方案3】:

      关键是您正在迭代中创建“item”变量。当您进行下一次调用时,您丢失了父进程的值,因为 eu 正在再次注册它,因此您必须在函数外部创建它并在内部使用引用。看:

      // 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"

      【讨论】:

        猜你喜欢
        • 2020-09-09
        • 1970-01-01
        • 2018-10-31
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 2023-03-26
        • 1970-01-01
        相关资源
        最近更新 更多