Skip to content

Commit

Permalink
[LINKED LISTS]: C++ solution to "medium" puzzle "Sum of Linked Lists".
Browse files Browse the repository at this point in the history
  • Loading branch information
MericLuc committed Feb 11, 2021
1 parent e1c56e1 commit a7100bd
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Linked Lists/sum-of-linked-lists.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*!
* @brief Sum of Linked Lists
* From https://www.algoexpert.io/questions/Sum%20of%20Linked%20Lists
*/

class LinkedList {
public:
int value;
LinkedList* next{nullptr};

LinkedList(int p_val) : value(p_val) { }
};

LinkedList* sumOfLinkedLists(LinkedList* l1,
LinkedList* l2) {
LinkedList *ret{new LinkedList(0)}, *cur{ret};
int carry{0};
while ( l1 || l2 || carry ) {
cur->next = new LinkedList(carry);
cur = cur->next;
carry = 0;
if ( l1 ) { cur->value += l1->value; l1 = l1->next; }
if ( l2 ) { cur->value += l2->value; l2 = l2->next; }

if ( cur->value >= 10 ) { cur->value -= 10; carry = 1; }
}

return ret->next;
}

0 comments on commit a7100bd

Please sign in to comment.