关闭

2_Add Two Numbers

标签: leetcode
194人阅读 评论(0) 收藏 举报
分类:

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.
你可以假设这两个数值不是以0开头,也就是假设这两个数值是正常合法的

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

我的解:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        p = 0
        result = None
        current = None
        while True:
            addValue = l1.val + l2.val + p
            p = 0

            if addValue >= 10:
                addValue = addValue - 10
                p = 1

            node = ListNode(addValue)

            if result == None:
                result = node
                current = node
            else:
                current.next = node
                current = node

            l1 = l1.next
            l2 = l2.next

            if l1 == None or l2 == None:
                break

        if l1 == None and l2 == None:
            pass
        elif l1 == None or l2 == None:
            rest = None
            if l1 == None:
                rest = l2
            else :
                rest = l1

            while True:
                addValue = p + rest.val
                p = 0

                if addValue >= 10:
                    addValue = addValue - 10
                    p = 1

                node = ListNode(addValue)
                current.next = node
                current = node

                rest = rest.next
                if rest == None:
                    break


        if p == 0:
            return result
        else:
            node = ListNode(p)
            current.next = node
            return result

看了答案才知道可以更简洁一些的 ~_~

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:90457次
    • 积分:2310
    • 等级:
    • 排名:第17503名
    • 原创:136篇
    • 转载:56篇
    • 译文:0篇
    • 评论:26条
    博客专栏