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 #-*-coding:utf-8-*- 2 3 #Definition for singly-linked list. 4 class ListNode(object): 5 def __init__(self, x): 6 self.val = x 7 self.next = None 8 9 class Solution(object): 10 def addTwoNumbers(self, l1, l2): 11 """ 12 :type l1: ListNode 13 :type l2: ListNode 14 :rtype: ListNode 15 """ 16 tens = 0 # l1.val+l2.val所得和的十位数,初始化0 17 units = 0 # l1.val+l2.val所得和的个位数,初始化0 18 l_origin = ListNode(0) # 表示一个链表的头结点 19 l = l_origin 20 while(l1 or l2 or tens!=0): 21 val = tens 22 if l1: 23 val = val + l1.val 24 l1 = l1.next 25 if l2: 26 val = val + l2.val 27 l2 = l2.next 28 units = val % 10 29 tens = val / 10 30 node = ListNode(units) 31 l.next = node 32 l = l.next 33 return l_origin.next # 返回所求列表
在Leetcode上提交时直接提交Solution类,结点定义不用提交。
在做这题时用到带有头结点的链表,比不带头结点的链表使用时方便的多。