javascript初探LeetCode之2.Add Two Numbers

题目

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

分析

这是leetcode上的第2题,难度为medium,就是实现两个ListNode结构(题目在代码中已给出)的链表的加法。

js实现

/*
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    var carry = 0;//carry存放进位
    var result = new ListNode(),temp = new ListNode();
    result.next = temp;//主要是想用result记录结果链表的表头
    var v1 = l1,v2 = l2;
    while(v1||v2){
        var sum = (v1?v1.val:0)+(v2?v2.val:0)+carry;  
        //v1?v1.val:0是考虑l1和l2可能不等长    
        carry = sum > 9 ? 1 : 0;
        temp.val = sum - carry * 10;//某一位上最终值
        temp.next = (v1?v1.next:null)||(v2?v2.next:null)?(new ListNode()):(carry==1?(new ListNode(1)):null);
        //l1或l2未遍历完,则新建一个ListNode结点;否则检查carry==1判断此时是否有进位,有则也需新建一个ListNode结点,
        //val置1,next置null,以上情况除外,则当前节点temp的next置null
        temp = temp.next?temp.next:null;
        //temp向后移动
        v1 = v1?(v1.next?v1.next:null):null;
        //v1存在且v1.next存在,就继续遍历,否则置null,下面v2类似,双重判断也是考虑考虑l1和l2可能不等长
        v2 = v2?(v2.next?v2.next:null):null;
    };
    return result.next;
};

总结

这一题思路简单,但是要注意题目中ListNode的结构,我的做法判断容易理解,但是判断较多,有更优解欢迎交流~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,348评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,394评论 0 23
  • 38岁那年,我偷偷报名了心理学的在职研究生。 我的求学经历,说起来也是有波折的。真是这样的波折,使得我心中有许多遗...
    老丁子阅读 16,924评论 6 5
  • 希望你只是烟云 在我心里缓缓掠过 你曾温柔抚摸过我脸庞 也曾深情为我遮蔽艳阳 你知道的 我喜欢你 挥之不去的烟丝 ...
    江小妖阅读 1,625评论 0 0
  • “网上还流传过一个段子:“所谓的婚姻,就是有时候很爱他,有时候想一枪崩了他。大多时候是在买枪的路上,遇到了他爱吃的...
    我是松鼠酱阅读 1,508评论 0 1