Add Two Numbers Stored in Forward Order
Implement addTwoNumbers
You're given two non-empty linked lists,
l1 and l2, each representing a non-negative integer with its digits stored in the usual order — the head node holds the most significant digit. Add the two numbers and return the sum as a linked list in that same forward order.
Unlike the reverse-order version of this problem, the head here is the most significant digit — the one that might need to change if a carry ripples all the way through, which a singly linked list can't easily do while reading forward. A stackStack for Order ReversalPushing every element of a sequence onto a stack and then popping them back off visits them in reverse order — without ever touching or reversing the original structure. It's a common alternative to in-place reversal when the original data needs to stay untouched. flips the visiting order to least-significant-first — matching how addition naturally carries — without disturbing either input list.
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9], l2 = [1]
Output: [1,0,0,0]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in l1, l2 ≤ 100 - ●
0 ≤ node value ≤ 9 - ●
Each list represents a non-negative integer with digits stored in the usual left-to-right order — the head is the most significant digit — and has no leading zeros, except the number 0 itself
l1 =
[7, 2, 4, 3]
l2 =
[5, 6, 4]