Add Two Numbers As Linked Lists

You are given two linked lists representing two non-negative numbers. The digits in the linked list are stored in reverse order, i.e. starting from least significant digit (LSD) to the most significant digit (MSD), and each of their nodes contains a single digit. Your task is to find the sum list and return the head of the sum list where the sum list is a linked list representation of the addition of two numbers.

Note :
The number represented by the linked lists do not contain any leading zeros. 
Input Format:
The first line of input contains a single integer T, representing the number of test cases. 

Then the T test cases follow.

The first line of each test case contains the elements of the first singly linked list separated by a single space and terminated by -1.

The second line of each test case contains the elements of the second singly linked list separated by a single space and terminated by -1.
Output Format:
For each test case, print the sum linked list. The elements of the sum list should be single-space separated and terminated by -1.

The output of each test case must be printed on a separate line.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function. 
Constraints :
1 <= T <= 10
1 <= M, N <= 5 * 10^4
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.

Time Limit: 1 sec
CodingNinjas
author
2y
Recursion
  • A simple approach could be to recursively add the nodes of the linked list while keeping track of the carry generated.
  • The idea behind this approach is the same as finding the sum of two numbe...read more
CodingNinjas
author
2y
Iterative Approach
  • The idea behind this approach is exactly similar to the previous approach. But here, instead of using recursion, we add the two linked lists iteratively.

The steps are as follows:

  • Le...read more
CodingNinjas
author
2y
Observation for Space Optimization
  1. The idea behind this approach is exactly similar to the previous approach. But here, instead of creating a new list for storing the sum, we use any one of the two lin...read more
Add answer anonymously...
TCS Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter