Tutorialspoint
Problem
Solution
Submissions

Add Two Numbers

Certification: Intermediate Level Accuracy: 50% Submissions: 4 Points: 10

Write a C program to add two numbers represented by linked lists. The digits are stored in reverse order, and each node in the linked list contains a single digit. You need to add the two numbers and return the sum as a linked list. Assume the two numbers do not contain any leading zero, except the number 0 itself.

Example 1
  • Input: l1 = [2,4,3], l2 = [5,6,4]
  • Output: [7,0,8]
  • Explanation: The numbers represented by the linked lists are 342 and 465 (in reverse order). 342 + 465 = 807 The result 807 is represented as [7,0,8] in reverse order.
Example 2
  • Input: l1 = [0], l2 = [0]
  • Output: [0]
  • Explanation: Both linked lists represent the number 0. 0 + 0 = 0 The result 0 is represented as [0] in the output linked list.
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
  • The two linked lists may have different lengths
  • You must solve the problem without modifying the input linked lists
  • Time Complexity: O(max(m,n)), where m and n are the lengths of the two lists
  • Space Complexity: O(max(m,n)), where m and n are the lengths of the two lists
Linked ListTCS (Tata Consultancy Services)EY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Traverse both linked lists simultaneously and add the digits at the corresponding positions
  • Keep track of the carry value when the sum of two digits exceeds 9
  • Create a new linked list to store the result
  • Continue the traversal until both linked lists are completely traversed
  • Remember to handle the carry value after traversing both lists

Steps to solve by this approach:

 Step 1: Create a dummy head node to simplify handling the result list.

 Step 2: Initialize a carry variable to 0 to keep track of any carry from adding digits.
 Step 3: Iterate through both lists simultaneously until both lists are exhausted and there's no carry left.
 Step 4: For each iteration, extract the digit from each list (or use 0 if the list is exhausted).
 Step 5: Add the digits along with the carry from the previous addition.
 Step 6: Create a new node with the value as the sum modulo 10 and update the carry as the sum divided by 10.
 Step 7: Move to the next nodes in both input lists and continue the process.

Submitted Code :