Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions linked_list_problems/add_two_numbers_lists.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ ListNode * addLists( ListNode * list1, ListNode *list2 )
ListNode *list3 = nullptr;
ListNode *curr = nullptr;
int carry = 0;

// both list1 and list2 are not null
while ( list1 && list2 ) {
int x = list1->val + list2->val + carry;
if ( x > 9 ) {
carry = x / 10;
x %= 10;
carry = 1;
x -= 10;
} else {
carry = 0;
}
Expand All @@ -45,23 +47,26 @@ ListNode * addLists( ListNode * list1, ListNode *list2 )
list2 = list2->next;
}

// list2 is null
while(list1) {
int x = list1->val + carry;
if ( x > 9 ) {
carry = x / 10;
x %= 10;
carry = 1;
x -= 10;
} else {
carry = 0;
}
curr->next = new ListNode(x);
curr = curr->next;
list1 = list1->next;
}

// list1 is null
while(list2) {
int x = list2->val + carry;
if ( x > 9 ) {
carry = x / 10;
x %= 10;
carry = 1;
x -= 10;
} else {
carry = 0;
}
Expand Down