Linked-List
Q1: Add Two Numbers
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* nxt = new ListNode();
ListNode* root = nxt;
int quotient = 0;
while(l1 != nullptr && l2 != nullptr) {
int sum = l1 -> val + l2 -> val + quotient;
nxt -> next = new ListNode(sum % 10);
nxt = nxt->next;
quotient = sum / 10;
l1 = l1->next;
l2 = l2->next;
}
if(l1 != nullptr) {
while(l1 != nullptr) {
int sum = l1 -> val + quotient;
nxt -> next = new ListNode(sum % 10);
nxt = nxt->next;
quotient = sum / 10;
l1 = l1->next;
}
}
else if(l2 != nullptr) {
while(l2 != nullptr) {
int sum = l2 -> val+quotient;
nxt -> next = new ListNode(sum % 10 );
nxt = nxt->next;
quotient = sum / 10;
l2 = l2->next;
}
}
if(quotient > 0)
nxt -> next = new ListNode(quotient);
return root -> next;
}
};
Last updated
Was this helpful?