LeetCode#2 Add two numbers
2017-10-20 本文已影响3人
夹小欣
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
这道题看了别人的码之后才通过了,对python语言本身不熟悉。
普通思路是一个一个加法,设置标志位
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
#头节点
p = first = ListNode(0)
#标志位
flag = 0
#如果最后有进位还是要输出的
#比如l1=9 l2=1 输出[0 1]
while l1 or l2 or flag:
val = (l1.val if l1 else0)+(l2.val if l2 else0)+flag
flag = val/10
p = ListNode(val%10)
if l1: l1 = l1.next
if l2: l2 = l2.next
if p: p=p.next
return first.next
另一个思路明天看,洗洗睡