【问题标题】:Leetcode Add Two Numbers Q: how to create a linkedlist from a number?Leetcode 两个数字相加 Q:如何从一个数字创建链表?
【发布时间】:2018-05-20 17:54:45
【问题描述】:

在这个问题中: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

【问题讨论】:

    标签: javascript algorithm linked-list


    【解决方案1】:

    如果你把你的号码变成一个数组,那么你可以使用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
    }

    【讨论】:

    • 你真的不应该需要那个slice(1)。只需传递null 作为初始值并使用reduceRight
    • @user184994,差不多。 LL 应该是相反的顺序。从那些开始,然后是几十、几百……所以只需将 reduceRight 改回 reduce 就可以了;)
    • @Thomas 哦,我没有注意到 OP 需要倒退列表。
    • @Bergi 这在您最近的编辑后不再有效 - head 未定义。您需要致电 new ListNode 而不是 ListNode
    • @user184994 哎呀,我不是要删除new。感谢您的测试:-)
    【解决方案2】:

    使用递归更容易:

    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 } } } ) )

    【讨论】:

    • 所有字母代表什么?
    • f = n => nfunction f(n) { return n } 的缩写,我用ab 代替了l1l2 参数。 c 只是一个临时变量,如果 2 位数字之和大于 9,则用于结转 +1。您可以在 typescriptlang.org/play/… 上查看翻译版本
    • n / 10 | 0 是如何工作的?我只是安慰了807 / 10 | 0,它给了我80,但不知道它是如何工作的
    • @cryptofish123 这是将浮点数转换为整数blog.blakesimpson.co.uk/read/… 的快捷方式之一。抱歉让代码如此神秘......我打算使用“Leet”代码:D
    • 您能解释一下c > 9 的工作原理吗?第三次迭代c = 10。我假设您只想将1 延续到下一次迭代?它是如何做到的?
    猜你喜欢
    • 2020-04-16
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2018-10-25
    相关资源
    最近更新 更多