把一個鏈表鏈接到另外一個鏈表的末尾。系列目錄見 前言和目錄 。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 }
循環的思路是,在 listA
和 listB
都不爲空的狀況下,先找到 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