Add two number as linked lists

You have been given two singly Linked Lists, where each of them represents a positive number without any leading zeros.

Your task is to add these two numbers and print the summation in the form of a linked list.

Example:
If the first linked list is 1 -> 2 -> 3 -> 4 -> 5 -> NULL and the second linked list is 4 -> 5 -> NULL.

The two numbers represented by these two lists are 12345 and 45, respectively. So, adding these two numbers gives 12390. 

So, the linked list representation of this number is 1 -> 2 -> 3 -> 9 -> 0 -> NULL.
Input format:
The first line of input contains an integer 'T' representing the number of test cases. 

The first line of each test case contains the elements of the first linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.

The second line of each test case contains the elements of the second linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
Output format:
For each test case, return the head of linked list after summation. The elements of the linked list must be terminated by -1.
Note:
You don't need to print anything, it has already been taken care of. Just implement the given function.
Follow-Up:
Try to solve this problem in linear time complexity and constant space complexity.
Constraints:
1 <= T <= 100
1 <= L <= 5000
0 <= data <= 9 and data != -1

Where 'L' is the number of nodes in either of the two Linked List and 'data' is the element value in a node of the linked list.

Time limit: 1 sec
CodingNinjas
author
2y
Naive Method

We will use the naive method to add two linked lists. While adding two numbers, we always add digits in the right to left manner. So first, we will reverse both linked lists so that we can...read more

CodingNinjas
author
2y
Constant Space

We will use the same naive method to add two linked lists. Like the previous approach, we will reverse both linked lists so that we can easily process the number in this manner.

Now, we ...read more

Help your peers!
Add answer anonymously...
Publicis Sapient Full Stack 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