Solution Review: Sum Two Linked Lists
This lesson contains the solution review for the challenge of summing two linked lists.
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 #
Press + to interact
def sum_two_lists(self, llist):p = self.headq = llist.headsum_llist = LinkedList()carry = 0while p or q:if not p:i = 0else:i = p.dataif not q:j = 0else:j = q.datas = i + j + carryif s >= 10:carry = 1remainder = s % 10sum_llist.append(remainder)else:carry = 0sum_llist.append(s)if p:p = p.nextif q:q = q.nextreturn 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 ...