Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Reason: 342 + 465 = 807
The topic introduction is still relatively simple, this question is also relatively simple, you need to pay attention to:
To maintain the integrity of the linked list, the final Next value must be none
Carry problem, there may be a carry
Finally, the official problem solution can't be solved with python3, and python2 is recommended. As for the reason, I didn't figure it out overnight!
# Definition for singly-linked list.
# classListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
classSolution(object):
def addTwoNumbers(self, l1, l2):"""
: type l1: ListNode
: type l2: ListNode
: rtype: ListNode
"""
p = l1
q = l2
res =ListNode(0)
r = res
s =0 #carry
# Of course, it can also be made into a lead node and returned to res.next
while(p!=None or q!=None):
p_v =0if p==None else p.val
q_v =0if q==None else q.val
r_v =(p_v+q_v+s)%10
s =(p_v+q_v+s)//10
r.next =ListNode(r_v)
r = r.next
r.next = None
# If it is not None, continue to traverse, otherwise stop traversing
p =p if p==None else p.next
q =q if q==None else q.next
if s !=0:
r.next =ListNode(s)
r = r.next
r.next = None
return res.next
Recommended Posts