Search⌘ K

Solution Review: Sum Two Linked Lists

Explore how to sum two singly linked lists by examining a Python implementation. Understand node traversal, handling carries, and appending results to create a new linked list that represents the sum.

We'll cover the following...

In this lesson, we investigate how to sum two singly linked lists. Check out the code below, after which, we will do a line by line analysis of it.

Implementation #

Python 3.5
def sum_two_lists(self, llist):
p = self.head
q = llist.head
sum_llist = LinkedList()
carry = 0
while p or q:
if not p:
i = 0
else:
i = p.data
if not q:
j = 0
else:
j = q.data
s = i + j + carry
if s >= 10:
carry = 1
remainder = s % 10
sum_llist.append(remainder)
else:
carry = 0
sum_llist.append(s)
if p:
p = p.next
if q:
q = q.next
return sum_llist

Explanation #

First of all, we initialize p and q to point to the heads of each of the two linked lists (lines 2-3). On line 5, we declare sum_llist and initialize it to a linked list. The data values of ...