用 JavaScript 實現鏈表操做 - 07 Append

TL;DR

把一個鏈表鏈接到另外一個鏈表的末尾。系列目錄見 前言和目錄javascript

需求

實現一個 append() 函數,把兩個鏈表鏈接起來,並返回鏈接後的鏈表頭結點。java

var listA = 1 -> 2 -> 3 -> null
var listB = 4 -> 5 -> 6 -> null
append(listA, listB) === 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null

若是兩個鏈表都是 null 就返回 null ,若是其中一個是 null 就返回另外一個鏈表。node

遞歸版本

append 自己就能夠做爲遞歸的邏輯。append(listA, listB) 實際上等於 listA.next = append(listA.next, listB) ,直到 listA 遞歸到末尾 null ,這時 append(null, listB) 直接返回 listB 便可。加上邊界條件判斷,代碼以下:git

function append(listA, listB) {
  if (!listA) return listB
  if (!listB) return listA

  listA.next = append(listA.next, listB)
  return listA
}

循環版本

循環的思路是,在 listAlistB 都不爲空的狀況下,先找到 listA 的尾節點,假設爲 node ,而後 node.next = listB 便可。代碼以下:github

function appendV2(listA, listB) {
  if (!listA) return listB
  if (!listB) return listA

  let node = listA
  while (node.next) node = node.next

  node.next = listB
  return listA
}

參考資料

Codewars Kata
GitHub 的代碼實現
GitHub 的測試segmentfault

相關文章
相關標籤/搜索