LeetCode No.2 Add Two Numbers 20170305

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.

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

难度:medium

题目大意:有两个数字被倒序的保存在两个链表中,请按照正常顺序输出两个数字求和的结果。

思路:如果两个链表都不为空,由于倒序之后,如今的最高位其实是原来的最低位,所以直接将两个链表的第一个元素与存储进位的变量carry相加,新的链表存储求和结果除以10的余数,carry等于求和结果除以10取整,保存新的进位结果。如果其中一个链表为空,则直接输出另一个链表剩余内容。如果两个链表都为空,则检查进位变量carry,如果carry不等于0,则将carry的值加入到输出链表中。

class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
List1=ListNode(0)
temp=List1
carry=0
while l1!=None and l2!=None:
temp.next=ListNode((l1.val+l2.val+carry)%10)
carry=(l1.val+l2.val+carry)/10
l1=l1.next
l2=l2.next
temp=temp.next
if l1!=None:
while l1!=None:
temp.next=ListNode((l1.val+carry)%10)
carry=(l1.val+carry)/10
l1=l1.next
temp=temp.next
if l2!=None:
while l2!=None:
temp.next=ListNode((l2.val+carry)%10)
carry=(l2.val+carry)/10
l2=l2.next
temp=temp.next
if carry!=0:
temp.next=ListNode(1)
return List1.next

这题考察的是链表的操作,难点应该在于如何处理某个链表变为空的情况,尤其是当两个链表同时变为空的时候,要检查进位是0还是1,如果是1的话要将进位结果加入到链表中去。

原文地址:https://www.cnblogs.com/fangdai/p/6505668.html