Issue
The following is my code which tries to add the two numbers, which are also stored in a linked list in reverse order, and returns the sum as a linked list.
But when I try to run this code in LeetCode, it states this exceeds the time. I assume that it may get stuck in the while loop?
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = ListNode()
carry = 0
while l1 != None or l2 != None or carry:
if l1 == None:
v1 = 0
else:
v1 = l1.val
if l2 == None:
v2 = 0
else:
v2 = l2.val
total = v1 + v2 + carry
carry = total // 10
total = total % 10
result.next = ListNode(total)
if l1 != None:
l1.next
if l2 != None:
l2.next
return result
Solution
There were few things only which I have changed in the code you wrote.
result = ListNode(0)
result_tail = result #### added
carry = 0
while l1 or l2 or carry:
if l1 == None:
v1 = 0
else:
v1 = l1.val
if l2 == None:
v2 = 0
else:
v2 = l2.val
total = v1 + v2 + carry
carry = total // 10
total = total % 10
result_tail.next = ListNode(total) ### edited
result_tail = result_tail.next ### added
if l1 != None:
l1 = l1.next ### edited
else:
l1 = None ### added
if l2 != None:
l2 = l2.next ### edited
else:
l2 = None ### added
return result.next ### edited
The major thing I wish you to know is that when you wrote l1.next
then you are just giving a command which needs a variable to store the value thus the changes go l1 = l1.next
.
Similarly, when you wrote the same statement you need a counter else statement where you need to address the condition when if condition fails. Since that condition was not present, the while loop runs infinitely.
The final part is where I added a result_tail
. By giving a try and error, I saw that if we are not adding it then the values of the result get updated instead of getting appended.
Lastly, It is not a dumb question. Just a friendly suggestion, if you are super new, instead of writing the medium-level code start with easy codes of all concepts. It will help you to know more about specific deals in python like the dictionary, default dictionary, list comprehension, list traversing, tuples, sets, enumerators and all. You may have done competitive coding earlier but to be honest, a new innings always starts on 0.
Answered By - Shikhar Gupta
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.