Monday, July 17th

 Adding two numbers represented by linked lists is the problem of the day

Given two linked lists representing two non-negative numbers, with the most significant digits at the beginning of the list, add the two numbers together and return the sum as a linked list

There are multiple ways to solve this problem.  We will solve it by reversing the linked lists so least significant digits are first, pad a list with zeros so they're the same size, then add the two together while accounting for a carry bit

First, reverse the lists

        ListNode *ptr1 = l1, *ptr2 = l2;
while(ptr1 != NULL || ptr2 != NULL){
if(ptr1 == NULL){ // if the end of list 1, pad it with zeros while traversing ptr2
ListNode *newNode = new ListNode(0);
newNode->next = l1;
l1 = newNode;
ptr2 = ptr2->next;
}
else if(ptr2 == NULL){
ListNode *newNode = new ListNode(0); //ditto with list 2, pad with zeros if empty
newNode->next = l2;
l2 = newNode;
ptr1 = ptr1->next;
}
else{ // if neither are empty then continue traversal
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}

} 

With the linked lists reversed, then we add them together.  This requires a new linked list to store the result, and a variable to store whether or not a carry is generated by adding to digits to 10 or greater

        int carry = 0;
ListNode *dummy = new ListNode(-1);

A recursive function to add together linked lists

    ListNode* addTwoDigit(ListNode* l1, ListNode* l2, int &carry){
if(l1 == NULL && l2 == NULL) return NULL;
ListNode *newNode = new ListNode(-1);
newNode->next = addTwoDigit(l1->next, l2->next, carry);
newNode->val = (l1->val + l2->val + carry) % 10;
carry = (l1->val + l2->val + carry) / 10;
return newNode;
}

Call the function, and if a carry bit is generated, add a new node to the linked list.  return the result

        dummy->next = addTwoDigit(l1, l2, carry);
if(carry != 0){
ListNode *newNode = new ListNode(carry);
newNode->next = dummy->next;
dummy->next = newNode;
}
return dummy->next;

Based off shared solutions 

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th