• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
卿与
博客园    首页    新随笔    联系   管理    订阅  订阅
2. 两数相加
LeetCode 2. 两数相加 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

2. 两数相加

题目描述

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:
  • 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
  • 输出:7 -> 0 -> 8
  • 原因:342 + 465 = 807

题解

这道题目给出的是两个链表的头。
要求输出的是求出的目的链表的头。

python代码
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        L2 = ListNode(0)  # 创建一个头节点
        L = L2  # 把头节点保留下来
        c = 0  # 进位标志
        while l1 is not None or l2 is not None:
            if l1 is not None and l2 is not None:  # 当两个连表都不为空时
                L0 = ListNode(0)  #先创建一个新的链表
                L0.val = (c + l1.val + l2.val) % 10
                c = (c + l1.val + l2.val) // 10
                L.next = L0  # 把新创建的节点接到目的链表的最后一个节点的next
                L = L.next  # 将三个链表都向后移动一个
                l1 = l1.next
                l2 = l2.next
            elif l2 is not None:
                L0 = ListNode(0)
                L0.val = (c + l2.val) % 10
                c = (c + l2.val) // 10
                L.next = L0
                L = L.next
                l2 = l2.next
            else:
                L0 = ListNode(0)
                L0.val = (c + l1.val) % 10
                c = (c + l1.val) // 10
                L.next = L0
                L = L.next
                l1 = l1.next

        if c != 0:  # 若最高有进位则再创建一个节点
            L.next = ListNode(c)

        L2 = L2.next  # 头结点里的数据不具有意义,不要!
        return L2
python完整代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        L2 = ListNode(0)
        L = L2
        c = 0
        while l1 is not None or l2 is not None:
            if l1 is not None and l2 is not None:
                L0 = ListNode(0)
                L0.val = (c + l1.val + l2.val) % 10
                c = (c + l1.val + l2.val) // 10
                L.next = L0
                L = L.next
                l1 = l1.next
                l2 = l2.next
            elif l2 is not None:
                L0 = ListNode(0)
                L0.val = (c + l2.val) % 10
                c = (c + l2.val) // 10
                L.next = L0
                L = L.next
                l2 = l2.next
            else:
                L0 = ListNode(0)
                L0.val = (c + l1.val) % 10
                c = (c + l1.val) // 10
                L.next = L0
                L = L.next
                l1 = l1.next

        if c != 0:
            L.next = ListNode(c)

        L2 = L2.next
        return L2

def stringToIntegerList(input):
    return json.loads(input)

def stringToListNode(input):
    # Generate list from the input
    numbers = stringToIntegerList(input)

    # Now convert that list into linked list
    dummyRoot = ListNode(0)
    ptr = dummyRoot
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummyRoot.next
    return ptr

def listNodeToString(node):
    if not node:
        return "[]"

    result = ""
    while node:
        result += str(node.val) + ", "
        node = node.next
    return "[" + result[:-2] + "]"

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            l1 = stringToListNode(line);
            line = next(lines)
            l2 = stringToListNode(line);
            
            ret = Solution().addTwoNumbers(l1, l2)

            out = listNodeToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()
posted on 2020-02-21 10:17  卿与  阅读(65)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3