Leetcode 2 add two numbers Python

Two non-empty linked lists are given to represent two non-negative integers. Among them, their respective digits are stored in reverse order, and each node can only store one digit.

If we add these two numbers together, a new linked list will be returned to represent their sum.

You can assume that none of these numbers start with 0 except for the number 0.

Example:

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:

  1. To maintain the integrity of the linked list, the final Next value must be none

  2. 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

Leetcode 2 add two numbers Python
python array add array_Python add array
Python classic interview questions two
Python basic drawing tutorial (two)
LeetCode brushing questions summary python3
How to filter numbers in python
​What are the numbers in Python?
How does python determine prime numbers