$[n]r]][“`python
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
Image: www.livemint.com
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
current = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
sum = val1 + val2 + carry
carry = sum // 10
current.next = ListNode(sum % 10)
current = current.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
“This code defines a
ListNodeclass to represent nodes in a linked list and a
Solutionclass that contains a method
addTwoNumbers` to add two linked lists representing non-negative integers. Here’s how this code works:
-
Define the
ListNode
class:- This class initializes a linked list node with a value (
val
) and a reference to the next node (next
).
- This class initializes a linked list node with a value (
-
Define the
Solution
class:- It contains a single method,
addTwoNumbers
, which takes two linked lists,l1
andl2
, as input.
- It contains a single method,
-
Creating a Dummy Node:
- A dummy node (in this case,
dummy
) is created with a value of 0 and is used as the starting point for the resulting linked list. - This node is initially pointed to by the
current
variable.
- A dummy node (in this case,
-
Initializing Variables:
- A variable called
carry
is initialized to 0. This variable will keep track of any carry that needs to be propagated to the next sum operation.
- A variable called
-
Iterative Loop:
- The loop continues as long as either
l1
,l2
, orcarry
is not None. - Inside the loop:
- The values of the current nodes in
l1
andl2
are obtained. If either of the lists has ended, the corresponding value is set to 0. - The sum of the current node values and
carry
is calculated and stored in thesum
variable. - The carry is updated by dividing
sum
by 10 and taking the remainder. - A new node is created with the value
sum % 10
and appended to thecurrent
node’snext
pointer. - The
current
node is updated to point to the newly created node. l1
andl2
are updated to point to their next nodes, orNone
if they have reached the end.
- The values of the current nodes in
- The loop continues as long as either
-
Return the Result:
- Once the loop completes, the
dummy.next
is returned, which points to the first node of the resulting linked list.
- Once the loop completes, the
This code effectively adds two non-negative integers represented as linked lists and returns the result as a new linked list.
Image: www.chinimandi.com
What Is Forex Reserves In Telugu