Algos Explained
A brief explanation of some popular algorithms
Leetcode problem 0002: Add two numbers
Iteration
One way to solve this problem is to iterate over the two linked lists and add the two node values together. If the sum of the two values is greater than or equal to 10, then there is a carry value that gets added in to the sum of the next iteration. If one linked list reaches the end before the other then we can ignore it until the other is finished as well.
Pseudocode
begin initialize L1_CURRENT = L1 initialize L2_CURRENT = L2 initialize CARRY = 0 create DUMMY_NODE initialize CURRENT = DUMMY_NODE while L1_CURRENT or L2_CURRENT contains nodes SUM = CARRY of previous iteration if L1_CURRENT contains nodes SUM += NODE value set L1_CURRENT = NODE.next if L2_CURRENT contains nodes SUM += NODE value set L2_CURRENT = NODE.next CARRY = SUM/10; create NEW_NODE with initial value = sum % 10 CURRENT.next = NEW_NODE CURRENT = CURRENT.next if CARRY != 0 create NEW_NODE with initial value = CARRY CURRENT.next = NEW_NODE return DUMMY_NODE.next end
Recursion
Another way to solve this problem is to use recursion. This method has the same logic as the iterative approach except that it recursively ads the next digit to the linked list. The benefit is that the code looks a little cleaner, but the draw back is the added space requirements due the recursive function calls.
Pseudocode
begin SUM = CARRY of previous recursive call if L1 contains NODE sum += NODE value L1 = L1.next if L2 contains NODE sum += NODE value L2 = L2.next create NEW_NODE with initial value = sum % 10 if L1 or L2 contains nodes OR SUM >= 10 NEW_NODE.next = return value of recursive function end