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
此题主要考链表,同时进位的考虑是重点。
考虑有一下几点:
1,链表长度相等
2,链表长度不相等
3,一直产生进位,如9999+1,需要建立新结点并追加其后
# 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
"""
l = l1
indent = 0
while l1.next and l2.next:
sum = l1.val + l2.val + indent
indent = sum / 10
val = sum % 10
l1.val = val
l1 = l1.next
l2 = l2.next
sum = l1.val + l2.val + indent
indent = sum / 10
val = sum % 10
l1.val = val
if l2.next: #l2链表长,转接到l1上
l1.next = l2.next
while l1.next: #l1链表长,循环依次处理进位
sum = l1.next.val + indent
indent = sum / 10
val = sum % 10
l1.next.val = val
l1 = l1.next
if indent: #最后产生的进位,增添新结点并追加
li = ListNode(indent)
l1.next = li
return l