Add Two Number Linked List Problem GFG
Given the head of two singly linked lists num1 and num2 representing two non-negative integers. The task is to return the head of the linked list representing the sum of these two numbers.
For example, num1 represented by the linked list : 1 -> 9 -> 0, similarly num2 represented by the linked list: 2 -> 5. Sum of these two numbers is represented by 2 -> 1 -> 5.
Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list.
Examples:
Input: num1 = 4 - > 5, num2 = 3 -> 4 -> 5
Output: 3 -> 9 -> 0
Explanation: Given numbers are 45 and 345. There sum is 390.
Input: num1 = 0 -> 0 -> 6 -> 3, num2 = 0 -> 7
Output: 7 -> 0
Explanation: Given numbers are 63 and 7. There sum is 70.
Constraints:
1 <= size of both linked lists <= 106
0 <= elements of both linked lists <= 9
class Solution {
// Function to reverse a linked list
static Node reverseNode(Node head) {
Node prev = null;
Node curr = head;
Node next = null;
while (curr != null) {
next = curr.next; // Store next node
curr.next = prev; // Reverse the link
prev = curr; // Move prev forward
curr = next; // Move curr forward
}
return prev;
}
static Node addTwoLists(Node num1, Node num2) {
// Reverse both linked lists
num1 = reverseNode(num1);
num2 = reverseNode(num2);
Node dummyHead = new Node(0);
Node tail = dummyHead;
int carry = 0;
while (num1 != null || num2 != null || carry > 0) {
int x = (num1 != null) ? num1.data : 0;
int y = (num2 != null) ? num2.data : 0;
int sum = x + y + carry;
carry = sum / 10;
tail.next = new Node(sum % 10);
tail = tail.next;
if (num1 != null) num1 = num1.next;
if (num2 != null) num2 = num2.next;
}
// Step 3: Reverse the result list
Node result = reverseNode(dummyHead.next);
// Step 4: Remove leading zeros (if any)
while (result != null && result.data == 0) {
result = result.next;
}
return (result == null) ? new Node(0) : result;
}
}
Comments
Post a Comment