I’m trying to write a function that sums integers, each of which are represented by a linked list where each node->data is a digit 0-9. The least significant digit is at the head of the list and the most is at the tail.
This is from the book Cracking the Coding Interview. Here is my code:
SinglyLinked<int>& addLists(SinglyLinked<int>& ll1, SinglyLinked<int>& ll2)
{
SinglyLinked<int> *sumList = new SinglyLinked<int>;
ListNode<int> *node1 = ll1.head; ListNode<int> *node2 = ll2.head;
int sum, carry = 0;
while(node1 || node2)
{
if(node1)
sum += node1->data;
if(node2)
sum += node2->data;
sum += carry;
carry = 0;
sumList->insertAtEnd(sum%10);
if(sum > 9)
carry = 1;
sum = 0;
node1 = node1->next; node2 = node2->next;
}
return *sumList;
}
First of all, is this code correct? It seems to work, but it seg faults when given two linked lists (integers) of different lengths. I’m wondering if the problem was only intended to solve for the case where the integers are of the same length. If not, how would I go about summing two lists of different lengths? My naive solution is to store the length of each list and then use that to create the digits which only one of the numbers will contribute to, until the two integers are aligned. Is there something more elegant than that?
It segfaults on different length lists, because then the
node1ornode2points to null.Change
to