1. 题目

Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)   
Output: 7 -> 0 -> 8        即342+465=807

给你两个链表代表两个非负数。数字以相反的顺序存储,每个节点包含一个单一的数字。加上这两个数并返回一个链表。

2.c++解题

 //LeetCode_Add Two Numbers
//Written by zhou
//2013.11.1 /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;         ListNode *resList = NULL, *pNode = NULL, *pNext = NULL; // resList头节点, pNode 每轮的末节点, pNext临时节点
        ListNode *p = l1, *q = l2;
        int up = 0;
        while(p != NULL && q != NULL)
        {
            pNext = new ListNode(p->val + q->val + up);
            up = pNext->val / 10;    //计算进位
            pNext->val = pNext->val % 10;   //计算该位的数字
            
            if (resList == NULL)  //头结点为空
            {
                resList = pNode = pNext;
            }
            else //头结点不为空
            {
                pNode->next = pNext;
                pNode = pNext;
            }
            p = p->next;
            q = q->next;
        }         //处理链表l1剩余的高位
        while (p != NULL)
        {
            pNext = new ListNode(p->val + up);
            up = pNext->val / 10;    
            pNext->val = pNext->val % 10;
            pNode->next = pNext;
            pNode = pNext;
            p = p->next;
        }         //处理链表l2剩余的高位
        while (q != NULL)
        {
            pNext = new ListNode(q->val + up);
            up = pNext->val / 10;    
            pNext->val = pNext->val % 10;
            pNode->next = pNext;
            pNode = pNext;
            q = q->next;
        }         //如果有最高处的进位,需要增加结点存储
        if (up > 0)
        {
            pNext = new ListNode(up);
            pNode->next = pNext;
        }         return resList;
    } };

3. python解题

3.1

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        dummy, flag = ListNode(0), 0
        head = dummy
        while flag or l1 or l2: //flag 进位, node临时节点, dummy最后节点
            node = ListNode(flag)
            if l1:
                node.val += l1.val
                l1 = l1.next
            if l2:
                node.val += l2.val
                l2 = l2.next
            flag = node.val / 10
            node.val %= 10
            head.next = node  
            head = head.next  # head.next, head = node, node
        return dummy.next

3.2

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
     if not l1: return l2
        if not l2: return l1
        dummy = ListNode(0)
        p = dummy
        flag = 0
        while l1 and l2:
            tmp = l1.val + l2.val + flag
            p.next = ListNode( tmp % 10 )
            flag = tmp / 10
            l1, l2, p = l1.next, l2.next, p.next
        if l1:
            while l1:
                tmp = l1.val + flag
                p.next = ListNode( tmp % 10 )
                flag = tmp / 10
                l1, p = l1.next, p.next
        if l2:
            while l2:
                tmp = l2.val + flag
                p.next = ListNode( tmp % 10 )
                flag = tmp / 10
                l2, p = l2.next, p.next
        if flag == 1: p.next = ListNode(flag)
        return dummy.next
     

4 java

public class Solution {  

    // Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
} public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ret = new ListNode(0);
ListNode cur = ret; int sum = 0;
while (true) {
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
cur.val = sum % 10;
sum /= 10;
if (l1 != null || l2 != null || sum != 0) {
cur = (cur.next = new ListNode(0));
} else {
break;
}
}
return ret;
}
}

leetcode——2的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  10. Leetcode 笔记 101 - Symmetric Tree

    题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...

随机推荐

  1. sql server 2008 r2安装

    选择功能(好像报错了-下次重装系统测试)

  2. [WIP]laravel 构成的概念

    创建: 2019/06/21 生命周期  概论    检索service provider               service container                     se ...

  3. go语言web开发框架_Iris框架讲解(六):Session的使用和控制

    在实际的项目开发中,我们会经常有业务场景使用到Session功能.在iris框架中,也为我们提供了方便使用,功能齐全的Session模块.Session模块的源码目录为kataras/iris/ses ...

  4. CSS布局那点事儿

    布局 最开始老的一代网站开发,布局都是通过表格实现的. 这样可以形成规整的网格布局,但是也会带来一定的复杂性.比如想要新增某个页面元素,就有可能要改动整个表格,添加很多无用的行或者列. 后来,衍生出不 ...

  5. Java学习笔记——Map接口

    Map接口 Map接口 Map接口中键和值一一映射. 可以通过键来获取值. 异常 NoSuchElementException:访问的值不存在 ClassCastException:对象类型错误 Un ...

  6. 微信小程序 —— 微信小程序解析html富文本插件wxParse

    下载并把wxParse放到小程序的目录中 github下载地址:https://github.com/icindy/wxParse 一.基本使用方法 1. Copy文件夹wxParse,把wxPars ...

  7. python之Selenium库的使用

    一  什么是Selenium selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并 ...

  8. Mysql遍历大表(Mysql大量数据读取内存溢出的解决方法)

    mysql jdbc默认把select的所有结果全部取回,放到内存中,如果是要遍历很大的表,则可能把内存撑爆. 一种办法是:用limit,offset,但这样你会发现取数据的越来越慢,原因是设置了of ...

  9. (jmeter内置可调用的变量)jmeter beanShell断言

    用户可以在jmeter- “beanShell断言”中自定义断言.自由灵活的用脚本实现自己的断言  beanShell断言接口介绍  在beanShell中直接可以调用的变量,无需加前缀.  1.lo ...

  10. @Inherited:允许子类继承父类的注解。

    在看定义注解的相关文章的时候,看到这个@Inherited注解,简单的说明并没有真正搞懂是什么意思.在网上搜索了一些相关的内容,现在把一篇文章转载过来.以便后面使用. 文章出处,转载地址:(http: ...