To add two numbers represented by linked lists, we need to first understand the properties of linked lists and how the data is represented.
A linked list is a common data structure where elements are nodes that contain two fields: a value and a pointer to the next node. To represent a number with a linked list we use each node to contain a single digit. The number 123 can be represented with a linked list as:
1 -> 2 -> 3
Let’s say we have two numbers represented as linked lists:
List1: 7 -> 1 -> 6 represents 617
List2: 5 -> 9 -> 2 represents 295
We want to perform the addition:
617
+ 295
-----
912
We can traverse both linked lists and keep adding corresponding nodes into a new linked list which forms the answer. The algorithm would look like this:
1. Initialize current node to dummy head of the returning list.
2. Initialize carry to 0.
3. Loop through lists l1 and l2 until you reach both ends.
- Set the value of l1 to node value if it is not None, else set it to 0.
- Set the value of l2 to node value if it is not None, else set it to 0.
- Calculate sum of values and the carry. If it’s above 10, set carry as 1 and reduce sum, if it’s not above 10, set carry as 0.
- Create a new node with the digit value of sum and set the next of current node to this new node.
- Advance current node to next.
- Advance both l1 and l2.
4. Check if carry is still left, if so create a new node with digit value of carry.
Here’s a Python code snippet that accomplishes this:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def addTwoLists(first, second):
# Initialize dummy Node
res = Node(0);
# Pointer to store the result
head = res;
# To store the carry after
# summing a node
carry = 0;
while(first is not None or second is not None or carry):
# At the start of each
# iteration, should be 0
# considering there is no
# number and carry from
# previous iteration
sum = 0;
# If first list is not None
if(first is not None):
sum += first.data;
first = first.next;
# If second list is not None
if(second is not None):
sum+=second.data;
second = second.next;
# Add carry from last iteration
sum += carry;
# Update carry
carry = sum // 10;
# Create a new node with sum
res.next = Node(sum % 10);
# Move pointer of resulting list
res = res.next;
# if any Nodes left in first list
if first:
res.next = first
# if any Nodes left in second list
if second:
res.next = second
return dummyHead.next
This code calculates the sum node by node from both the linked lists, and keeps track of the carry for each calculation. The time complexity of this solution is O(max(n, m)) where n and m are the lengths of the two linked lists. This is because we are processing each node from the two linked lists once. The space complexity is also O(max(n, m)) as we are allocating space for the new linked list.