0 0
Read Time:48 Second

Given two non-empty linked lists l1 and l2 and output in linked list rtype (linked list)

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Python Code Solution

# 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
        """
        str1=""
        while(l1.next!=None):
            str1=str1+str(l1.val)
            l1= l1.next
        str1=(str1+str(l1.val))[::-1]
        
        str2=""
        while(l2.next!=None):
            str2=str2+str(l2.val)
            l2= l2.next
        str2=(str2+str(l2.val))[::-1]
        
        z= int(str1)+int(str2)
        result=str(z)
        
        head=None
        for i in range(len(result)):
            head= ListNode(int(result[i]),head)
        return head

Thank You

For more about data structure in python : https://docs.python.org/3/tutorial/datastructures.html

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *