https://leetcode.com/problems/add-two-numbers/editorial/
On the leetcode website, there is a "Add Two Number" practice. My questions is, how does l1.val or l2.val work? I thought l1 is a list which is [2, 4, 3]. How does l1.val calling integer 2?
Or it’s from class ListNode? I’m confused..
Code solution as below:
Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummyHead = ListNode(0)
curr = dummyHead
carry = 0
while l1 != None or l2 != None or carry != 0:
l1Val = l1.val if l1 else 0
l2Val = l2.val if l2 else 0
columnSum = l1Val + l2Val + carry
carry = columnSum // 10
newNode = ListNode(columnSum % 10)
curr.next = newNode
curr = newNode
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummyHead.next
There are l1 = [2, 4, 3] and l2 = [5, 6, 4]. I thought to access the integer inside the list, you need to write l1[index]?
Why the code is using l1.val?
>Solution :
For brevity, they are written as lists, but they are not
If they really were simply list objects, you would be able to access the elements as l1[0] etc.
However they are in fact ListNode objects.
l1 is, in effect,
{
"val":2,
"next": {
"val":4,
"next": {
"val":3,
"next":None
}
}
}
They are just writing [2,4,3] as a shorthand for the above structure. I agree that it is confusing.
l1 and l2 are specified to be of type ListNode when defined
def addTwoNumbers(self, l1: Optional[ListNode], ...
##################
The code above means, "If parameter l1 is present, it is of type ListNode".
The definition of ListNode is given in the previous block, beginning class ListNode:.
In other words, class Solution depends on class ListNode.