提供如下两个链表:javascript
4 -> 5 -> 7 -> 8
与 3 -> 5 -> 8
,每个链表表明一个相反顺序的数字,所以:前端
4 -> 5 -> 7 -> 8
表明:8754java
3 -> 5 -> 8
表明:853node
请编写一个方法来将两个数字相加并将其做为另外一个链表返回?git
// list1: 4 -> 5 -> 7 -> 8
// list2: 3 -> 5 -> 8
addLLNums(list1, list2);
// 应该返回:7 -> 1 -> 6 -> 9
// 8764 + 853 = 9617
复制代码
// Available Data Structures
function Node(val) {
this.val = val;
this.next = null;
}
function LinkedListNode(val) {
this.val = val;
this.next = null;
}
var list1 = new LinkedListNode(3);
var nodes1 = [4, 5, 6, 7, 8, 9, 10];
createNodes(list1, nodes1);
var list2 = new LinkedListNode(1);
var nodes2 = [2, 3, 4, 5, 6, 7, 8];
createNodes(list2, nodes2);
function createNodes(head, nodes) {
for (let i = 0; i < nodes.length; i++) {
var newNode = new LinkedListNode(nodes[i]);
head.next = new newNode;
head = newNode;
}
}
/* * @param {LinkedListNode} list1 * @param {LinkedListNode} list2 * @return {LinkedListNode} */
function addLLNums(list1, list2) {
// add list1 and list2
return result;
}
复制代码