Add Two Numbers Represented as Linked Lists

Given two linked lists representing two non-negative integers, where the digits are stored in reverse order (i.e., starting from the least significant digit to the most significant digit), each node contains a single digit. Your task is to add these two numbers and return the head of the linked list representing the sum of the numbers.

Example:

Input:
TestCase 1: 
List1: 2 -> 4 -> 3 -> -1
List2: 5 -> 6 -> 4 -> -1
Output:
7 -> 0 -> 8 -> -1
Explanation:

The numbers are 342 and 465. The sum is 807, and the linked list representation of the sum is 7 -> 0 -> 8 -> -1

Input:

The first line contains an integer T, the number of test cases.
Each test case consists of:
- Two lines containing elements of the first and second linked list respectively, terminated by -1.

Output:

For each test case, output the summed linked list, with elements space-separated and terminated by -1.

Constraints:

  • 1 <= T <= 10
  • 1 <= M, N <= 5 * 104
  • 0 <= data[i] <= 9 and data[i] != -1

Where 'M' and 'N' are the number of nodes in the two linked lists, 'data[i]' is the data of the 'i-th' node.

Note: The numbers do not have leading zeros.

AnswerBot
4mo

Add two numbers represented as linked lists in reverse order and return the sum as a linked list.

  • Traverse both linked lists simultaneously, adding corresponding digits along with carry from previous s...read more

Help your peers!
Select
Add answer anonymously...
Associate Professional Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits