Yesterday, I recieved some help adding two linked lists of same length, and today I would like to tackle the problem of adding two different lengths. Example:
list 1: head->3->4->5->1->4;
list 2: head->4->3->1;
So if I start at both heads, I am fine until I reach list 2 Null. What do I need to consider, or do, to add list1's last two elements to list2's non existing last two elements?
If this was array, I would make a dummy array, set to zero and continue with the addition. Is there a similar method with linked lists to trick the compiler into addition?
Not really looking for code, just the methodology I need to apply and things to consider.
Pseudocode (because you aren't "really looking for code"):
function add(listPointer1, listPointer2)
while listPointer1 is not null or listPointer2 is not null
valueToAdd := 0
if listPointer1 is not null
valueToAdd := valueToAdd + listPointer1.number
listPointer1 := listPointer1.next
endif
if listPointer2 is not null
valueToAdd := valueToAdd + listPointer2.number
listPointer1 := listPointer2.next
endif
resultingList.add(valueToAdd)
endwhile
return resultingList
end function
You might as well think about the case that list1 is shorter than list 2 also.
I guess you have a choice to make, does the addition of these two equal this:
list 3: head->7->7->6
or this: list 3: head->7->7->6->1->4
First case is easier: While both nodes are not null, add the two together and increment both nodes.
2nd case has the same code as case one. But, when you reach a NULL node, you need to make new nodes and tack them onto list 3 from whichever list still has nodes left.