445. Add Two Numbers II
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
Constraints:
- The number of nodes in each linked list is in the range [1, 100].
- 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
From: LeetCode
Link: 445. Add Two Numbers II
Solution:
Ideas:
1. Stack Setup:
- Arrays stack1 and stack2 act as stacks to hold digits from l1 and l2.
- We push all values from each list into their respective stacks to reverse their order.
2. Addition with Carry Handling:
- We pop values from both stacks and add them along with any carry.
- After calculating the sum, we determine the next carry (carry = sum / 10) and the current digit (sum = sum % 10).
- We create a new node for this digit and add it at the head of the result list.
3. Final Carry Check:
- If there’s any leftover carry after processing both stacks, it’s handled in the last iteration of the loop.
Code:
/**
* Definition for singly-linked list.
*/
struct {
int val;
struct ListNode *next;
}ListNode;
// Function to push a value onto a stack
void push(int* stack, int* top, int value) {
stack[++(*top)] = value;
}
// Function to pop a value from a stack
int pop(int* stack, int* top) {
return stack[(*top)--];
}
// Helper function to create a new ListNode
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int stack1[101], stack2[101];
int top1 = -1, top2 = -1;
// Push values of l1 into stack1
while (l1 != NULL) {
push(stack1, &top1, l1->val);
l1 = l1->next;
}
// Push values of l2 into stack2
while (l2 != NULL) {
push(stack2, &top2, l2->val);
l2 = l2->next;
}
struct ListNode* result = NULL;
int carry = 0;
// Process both stacks
while (top1 >= 0 || top2 >= 0 || carry != 0) {
int sum = carry;
if (top1 >= 0) sum += pop(stack1, &top1);
if (top2 >= 0) sum += pop(stack2, &top2);
carry = sum / 10;
sum = sum % 10;
// Create a new node with the current sum and add it to the front of the result list
struct ListNode* newNode = createNode(sum);
newNode->next = result;
result = newNode;
}
return result;
}