簡體   English   中英

JavaScript:用於查找鏈接列表節點的遞歸函數返回錯誤的節點

[英]JavaScript: Recursive function used to find a Linked list node returns wrong node

為了更好地理解遞歸,我決定嘗試使用遞歸函數來查找鏈表中的項而不是while循環。

接近結束時,我的遞歸函數似乎是通過返回正確的節點做正確的事情,但然后它運行意外返回幾次(我不知道為什么)並返回一個不正確的對象。 我錯過了什么嗎?

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

你的功能應該是這樣的:

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)

你應該在if中捕獲遞歸函數的返回值。

做就是了

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

它按預期工作。

關鍵是你在迭代中創建了“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" 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM