leetcode002——两数相加(链表,python)
"""
Created on Wed May 22 09:25:47 2019
@author: Lenovo
"""
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
"""
re
= ListNode
(0)
r
=re
carry
=0
while(l1
or l2
):
x
= l1
.val
if l1
else 0
y
= l2
.val
if l2
else 0
s
=carry
+x
+y
carry
=s
//10
r
.next=ListNode
(s
%10)
r
=r
.next
if(l1
!=None):l1
=l1
.next
if(l2
!=None):l2
=l2
.next
if(carry
>0):
r
.next=ListNode
(1)
return re
.next
if __name__
=='__main__':
S
=Solution
();
l1
=ListNode
(2);l1
.next=ListNode
(4);l1
.next.next=ListNode
(3);
l2
=ListNode
(5);l2
.next=ListNode
(6);l2
.next.next=ListNode
(4);
r
=S
.addTwoNumbers
(l1
,l2
)
print(r
.val
,r
.next.val
,r
.next.next.val
)
转载请注明原文地址: https://yun.8miu.com/read-17969.html