Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find numbers represented as linked lists in Python
Suppose we have two singly linked lists L1 and L2, each representing a number with least significant digits first. We need to find their sum as a linked list.
For example, if L1 = [5,6,4] represents 465 and L2 = [2,4,8] represents 842, their sum is 1307, which should be returned as [7,0,3,1].
Algorithm
To solve this problem, we follow these steps ?
Initialize carry = 0 and create a dummy result node
Traverse both lists simultaneously while either list has nodes or carry exists
For each position, add the values and carry
Use divmod to get new carry and digit value
Create a new node with the digit and advance pointers
Return the result list (skipping dummy head)
Implementation
class ListNode:
def __init__(self, data, next=None):
self.val = data
self.next = next
def make_list(elements):
if not elements:
return None
head = ListNode(elements[0])
current = head
for element in elements[1:]:
current.next = ListNode(element)
current = current.next
return head
def print_list(head):
result = []
ptr = head
while ptr:
result.append(str(ptr.val))
ptr = ptr.next
print('[' + ', '.join(result) + ']')
class Solution:
def solve(self, L1, L2):
carry = 0
dummy = ListNode(0)
current = dummy
while L1 or L2 or carry:
val1 = L1.val if L1 else 0
val2 = L2.val if L2 else 0
total = val1 + val2 + carry
carry, digit = divmod(total, 10)
current.next = ListNode(digit)
current = current.next
L1 = L1.next if L1 else None
L2 = L2.next if L2 else None
return dummy.next
# Example usage
ob = Solution()
L1 = make_list([5, 6, 4]) # represents 465
L2 = make_list([2, 4, 8]) # represents 842
print("L1:", end=" ")
print_list(L1)
print("L2:", end=" ")
print_list(L2)
print("Sum:", end=" ")
print_list(ob.solve(L1, L2)) # represents 1307
L1: [5, 6, 4] L2: [2, 4, 8] Sum: [7, 0, 3, 1]
How It Works
The algorithm simulates addition digit by digit from right to left ?
Step 1: Add 5 + 2 = 7 (no carry)
Step 2: Add 6 + 4 = 10 (digit = 0, carry = 1)
Step 3: Add 4 + 8 + 1 = 13 (digit = 3, carry = 1)
Step 4: No more digits, but carry = 1, so add node with 1
The key insight is using divmod(total, 10) to simultaneously get the carry and the digit to store in the current node.
Time and Space Complexity
Time Complexity: O(max(m, n)) where m and n are lengths of the input lists
Space Complexity: O(max(m, n)) for the result list
Conclusion
This solution efficiently adds two numbers represented as linked lists by simulating manual addition. The use of a dummy head node simplifies the implementation and handles edge cases naturally.
