You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Input: l1 = [2,4,3], l2 = [5,6,4]
Input: l1 = , l2 = 
- The number of nodes in each linked list is in the range
0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
Follow up: Could you solve it without reversing the input lists?
Reverse the list and then add the LSB first.
traverse the linked list and add each corresponding node,
if any node is exhausted , then assume its value as 0 go on adding the corresponding element together with carry from,
Space :O(n) new linked list representing the sum value
Since stack works on LIFO method.
We put all values of l1 and l2 to 2 seperate stacks, and pop the elements and add it with carry from previous addition.
Note that if any of the stack is emptied first while popping , then further values from that stack is assumed as 0.
traverse the linked list
push l1 and l2 elements to the stack
pop the stack element and add them with carry
update new carry and also put the last digit of result to the new linked list
def addTwoNumbers(self, l1, l2):
while(ptr1 or ptr2):
while(one or two):
val1=one.pop() if one else 0
val2=two.pop() if two else 0
Note that ,the result is such that the head of resulting linked list point to the MSB of sum.
So, while linking the nodes, new nodes are inserted at front , rather than at end.
Space :O(n+n) stack space and new linked list representing the sum value.