Untitled

 avatar
unknown
plain_text
15 days ago
2.6 kB
3
Indexable
class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class AddTwoNumbers {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0); // Dummy node to simplify result list construction
        ListNode temp = dummy;
        int carry = 0;

        // Traverse both lists
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;

            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }

            // Calculate the new digit and update carry
            carry = sum / 10;
            temp.next = new ListNode(sum % 10);
            temp = temp.next;
        }

        return dummy.next; // Return the next node after the dummy
    }

    // Helper Method: Print Linked List
    public void printLinkedList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }

    // Helper Method: Create Linked List from Array
    public ListNode createLinkedList(int[] arr) {
        if (arr == null || arr.length == 0) return null;

        ListNode head = new ListNode(arr[0]);
        ListNode temp = head;

        for (int i = 1; i < arr.length; i++) {
            temp.next = new ListNode(arr[i]);
            temp = temp.next;
        }

        return head;
    }

    // Main Method: Test the Solution
    public static void main(String[] args) {
        AddTwoNumbers solution = new AddTwoNumbers();

        // Test Case 1
        int[] arr1 = {2, 4, 3};
        int[] arr2 = {5, 6, 4};
        ListNode l1 = solution.createLinkedList(arr1);
        ListNode l2 = solution.createLinkedList(arr2);

        ListNode result = solution.addTwoNumbers(l1, l2);
        System.out.print("Result: ");
        solution.printLinkedList(result); // Expected: 7 -> 0 -> 8 -> null

        // Test Case 2
        int[] arr3 = {9, 9, 9, 9, 9, 9, 9};
        int[] arr4 = {9, 9, 9, 9};
        l1 = solution.createLinkedList(arr3);
        l2 = solution.createLinkedList(arr4);

        result = solution.addTwoNumbers(l1, l2);
        System.out.print("Result: ");
        solution.printLinkedList(result); // Expected: 8 -> 9 -> 9 -> 9 -> 0 -> 0 -> 0 -> 1 -> null
    }
}
Leave a Comment