LeetCode Problem: Linkded List Topics
LeetCode Problem: Linkded List Topics
1. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself. For example:
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
Suppose the input lists are:
1 | l1: 2 -> 4 -> 3 -> 2 |
The initial carry is set to 0, and we can use two pointers to traverse the two lists at the same time:
1 | 2 -> 4 -> 3 -> 2 |
2 + 5 + carry = 7
, and the updated carry is 0. We can add 7%10 = 7
into the result list, and keep traversing the two lists:
1 | 2 -> 4 -> 3 -> 2 |
4 + 6 + carry = 10
, and the updated carry should be 1. We can add 10%10 = 0
into the result list, and keep traversing the two lists:
1 | 2 -> 4 -> 3 -> 2 |
3 + 4 + carry = 8
, and the updated carry is 0. We can add 8%10 = 8
into the result list, and keep traversing the two lists:
1 | 2 -> 4 -> 3 -> 2 |
2 + 0 + carry = 2
, and the updated carry is 0. We can add 2%10 = 2
into the result list, and keep traversing the two lists.
After traversing the two lists, the final carry is 0, therefore final result list is 7 -> 0 -> 8 -> 2
.
Here is the code:
1 | public class AddTwoNumbers { |