Add two numbers represented as Linked List - The Coding Shala

Home >> Interview Questions >> Add two numbers represented as linked list

Add two numbers represented as Linked List

Problem: 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 contains 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.



Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Add two numbers represented as Linked List Java Program

Approach 1:
Check carry at the end and check if the length is not the same for the linked list.

Java Code 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode ans = new ListNode(0);
        ListNode dummy = ans;
        while(l1 != null || l2 != null){
            int val1 = 0;
            int val2 = 0;
            if(l1 != null){
                val1 = l1.val;
                l1 = l1.next;
            }else{
                val1 = 0;
            }
            if(l2 != null){
                val2 = l2.val;
                l2 = l2.next;
            }else{
                val2 = 0;
            }
            int tt = val1 + val2 + carry;
            if(tt > 9){
                tt = tt%10;
                carry =1;
            }else carry =0;
            ListNode tmp = new ListNode(tt);
            dummy.next = tmp;
            dummy = dummy.next;
        }
        if(carry >0){
            ListNode tmp = new ListNode(1);
            dummy.next = tmp;
            dummy = dummy.next;
        }
        return ans.next;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala