minty_Brit666‘s python practice no.2
minty_Brit666
Today’s blog is about the practice of the leetcode.
And I’ll give my own answer in this blog.
You are given two non-empty linked lists representing two non-negative integers. Each digit is stored in reverse order, and only one digit can be stored per node. You add the two numbers and return a linked list representing the sum in the same form. You can assume that neither of these numbers will start with 0, except for the number 0.
Source: LeetCode
Link: https://leetcode-cn.com/problems/add-two-numbers
Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# Create a head node with the value of None, sum and a to point to, sum to return last, and a to traverse
sum = a = ListNode(None)
x = 0 # Initialize carry s to 0
while l1 or l2 or x:
# If l1 or L2 is present, take the value of L1 + the value of l2 + x(x is initially 0, if there is a carry 1 below, add it next time)
x += (l1.val if l1 else 0) + (l2.val if l2 else 0)
a.next = ListNode(x % 10)
# a.next points to the new list to create a new list
a = a.next
#a traverses backwards
x //= 10
# In the case of carry, take the modulus, eg. x = 12, 12 // 10 = 1
l1 = l1.next if l1 else None
#If l1 is present, it is traversed backwards, otherwise None
l2 = l2.next if l2 else None
# If L2 exists, it is traversed backwards, otherwise None
return sum.next
# Returns the next node of sum, since sum points to an empty head node, which is the next node in the new list
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sum = a = ListNode(None)
x = 0
while l1 or l2 or x:
x += (l1.val if l1 else 0) + (l2.val if l2 else 0)
a.next = ListNode(x % 10)
a = a.next
x //= 10
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return sum.next
The solution is derived from LeetCode user Mengzhihen.