Add Two Numbers as Lists

Medium

Given two natural numbers, a and b, represented as reversed linked lists, compute their sum c as another reversed linked list.

Example 1

Two numbers 132 and 541 are shown in the form of reversed linked lists, and so is their sum which is 673.

Add Two Numbers as Lists
Example 2

Input:
a: 321 :   1 → 2 → 3
b: 654 :   4 → 5 → 6

Output:
c: 975 :   5 → 7 → 9

Example 3

Input:
a: 501 :   1 → 0 → 5
b: 639 :   9 → 3 → 6

Output:
c: 1140 :   0 → 4 → 1 → 1

Testing

Input Format

For each test case, the input has three lines:

  • Two space-separated integers, ‘n’ and ‘m’, denoting the length of two numbers.
  • n space-separarted numbers denoting digits of ‘a’ in reverse order.
  • m space-separarted numbers denoting digits of ‘b’ in reverse order.

Output Format

For each test case, the output has a line with space separated digits of ‘c’ in reverse order.

Sample Input

4
3 3
3 4 5
1 0 1
1 4
3
1 2 3 4
3 3
3 4 5
3 0 1
1 2
3
3 4

Expected Output

4 4 6
4 2 3 4
6 4 6
6 4

Constraints

1 <= T <= 100
1 <= n, m <= 1000

Editorial Link: Editorial