Difficulty: Medium
Topics: Linked Lists, Mathematical Computation, Algorithm Design
Objective: Add two non-negative integers represented by linked lists and return the result as a linked list.
You are given two non-negative integers represented by two linked lists, where each node contains a single digit. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
Input:
l1 = [2, 4, 3]
, l2 = [5, 6, 4]
Output:
[7, 0, 8]
Explanation:
342 + 465 = 807. The sum is returned as a linked list, where the digits are reversed.
The code defines a C++ class called Solution
with a member function addTwoNumbers
. The function adds two numbers represented by linked lists and returns the result as a new linked list.
dummyHead
) is created to simplify list construction.l3
) is initialized to point to dummyHead
.l1
and l2
are extracted (or treated as 0 if the list is shorter).l3
is moved forward, and l1
and l2
are also advanced to the next nodes.Input:
l1 = [2, 4, 3]
, l2 = [5, 6, 4]
Output:
[7, 0, 8]
Explanation:
342 + 465 = 807, which is returned as a linked list: [7, 0, 8]
.
Input:
l1 = [9, 9, 9]
, l2 = [1, 1, 1]
Output:
[0, 1, 1, 1]
Explanation:
999 + 111 = 1110, which is returned as a linked list: [0, 1, 1, 1]
.
Input:
l1 = [1, 2]
, l2 = [9, 9, 9]
Output:
[0, 2, 0, 1]
Explanation:
12 + 999 = 1011, which is returned as a linked list: [0, 2, 0, 1]
.
Input:
l1 = []
, l2 = [5, 6, 4]
Output:
[5, 6, 4]
Explanation:
If one list is empty, the other list is returned as the result.
Input:
l1 = []
, l2 = []
Output:
[]
Explanation:
If both lists are empty, the result is an empty list.
https://leetcode.com/problems/add-two-numbers/
Loading component...
Loading component...
Main Function is not defined.
INPUT: l1 = [2,4,3], l2 = [5, 6, 4]
OUTPUT: [7,0, 8]
public static ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
ListNode* dummyHead = new ListNode(0);
ListNode* l3 = dummyHead;
int ex = 0;
while(l1 != nullptr || l2 != nullptr || ex != 0){
int digit1 = (l1 != nullptr)? l1 ->val :0;
int digit2 = (l2 != nullptr)? l2->val:0;
int data = digit1 + digit2 + ex ;
int sum = data % 10;
ex = data /10;
ListNode* temp = new ListNode(sum);
l3 -> next = temp;
l3 = l3 -> next;
l1 = (l1 != nullptr)? l1 ->next : nullptr
l2 = (l2 != nullptr)? l2 -> next: nullptr
}
ListNode* result = dummyHead -> next;
delete dummyHead;
return result;
}//function end
Utility Function is not required.