Leetcode添加两个数字问:如何从数字创建链表?

时间:2017-12-06 18:38:15

标签: javascript algorithm linked-list

在这个问题:https://leetcode.com/problems/add-two-numbers/description/中,我已经弄清楚如何获得数字的总和(即807),但现在我需要将该数字转换为链表(例如7 - > 0 - > 8)。

如何从数字创建链接列表?

用于创建列表节点的类函数:

function ListNode(val) {
   this.val = val;
   this.next = null;
}

我的其余代码:

var addTwoNumbers = function(l1, l2) {

    function findVal(linkedList) {
          return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);

    }

    var l1num = parseInt(findVal(l1).split('').reverse().join(''));
    var l2num = parseInt(findVal(l2).split('').reverse().join(''));
    var sum = l1num + l2num;

// Create linked list from sum

2 个答案:

答案 0 :(得分:2)

如果您将数字转换为数组,则可以使用array.prototype.reduce函数。



let number = 807;

function ListNode(val) {
  this.val = val;
  this.next = null;
}


// Convert the number into a string and split that into an array of digits
let arr = Array.from(number.toString());

// Iterate through the elements, and create the nodes
let head = arr.reduce((nextNode, curr) => {
  let node = new ListNode(curr);
  node.next = nextNode;
  return node;
}, null);


// Print out the values
let node = head;
while(node) {
  console.log(node.val);
  node = node.next
}




答案 1 :(得分:1)

递归更容易:



f = n => n ? { val: n % 10, next: f(n / 10 | 0) } : null

console.log( f(807) )






f = (a, b, c = 0) => a && b && { val: (c += a.val + b.val) % 10, 
                                next: f(a.next, b.next, c > 9) } || null

console.log( f( { val: 2, next: { val: 4, next: { val: 3 } } }, 
                { val: 5, next: { val: 6, next: { val: 4 } } } ) )