把一个链表链接到另外一个链表的末尾。系列目录见 前言和目录 。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