提供如下兩個鏈表: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;
}
複製代碼