You are given, linked lists representing, and non-negative numbers. The most significant digit comes first and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
You may assume the numbers does not contain any leading zero, except the number 0 itself.
Follow up:
What if cannot modify the input lists? In other words, reversing the lists are not allowed.
Example:
Input: (7, 2, 4, 3) + (5, 6, 4)Output: 7, 8, 0, 7
#Definition for singly-linked list.#class ListNode (object):#def __init__ (self, x):#self.val = x#Self.next = Noneclasssolution (object):defaddtwonumbers (self, L1, L2):""": Type L1:ListNode:type l2:ListNode:rtype:ListNodeInput: (7, 2, 4, 3) + (5-& Gt 6, 4) 77->2->4->3 5->6->4=-------------7->7->0->7->1 output:7, 8, 0 """S1,s2=[],[] p1,p2=L1,l2 whilep1:s1.append (p1.val) P1=P1.next whilep2:s2.append (p2.val) P2=P2.next Carry=0 Fake_head=ListNode (None) whileS1orS2orCarry:v1= S1.pop ()ifS1Else0 v2= S2.pop ()ifS2Else0 Val= v1 + v2 +CarryifVal >= 10: Val-= 10Carry= 1Else: Carry=0 Head=ListNode (val) head.next=Fake_head.next Fake_head.next=HeadreturnFake_head.next
445. Add, Numbers ii--while S1 or S2 or carry the topic again. Test Cases