AlgoDaily

Add Linked List Numbers

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

We're provided the following two linked lists:

1 -> 2 -> 3 -> 4 and 2 -> 5 -> 8

Each one represents a number in reversed order, so 1 -> 2 -> 3 -> 4 represents 4321 and 2 -> 5 -> 8 represents 852 (note: for an extra challenge, consider if they weren't reversed).

The lists are guaranteed to have at least one node and will not have any leading 0s. Each of the nodes contain a single digit.

Can you write a method to add the two numbers and return it as another linked list?

// list1: 1 -> 2 -> 3 ->4
// list2: 2 -> 5 -> 8

addLLNums(list1, list2);
// should return 3 -> 7 -> 1 -> 5
// 4321 + 852 = 5173

Constraints
  • Length of both linked lists list1, list2 <= 100000
  • Value stored in each node is between 0 and 9
  • Make sure that you have to return a linked list and not a number
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)
```js
/*
 * @param {LinkedListNode} list1
 * @param {LinkedListNode} list2
 * @return {LinkedListNode}
 */

function addLLNums(list1, list2) {
	// add list1 and list2
	return result;
}

function LinkedListNode(val) {
	this.val = val;
	this.next = null;
}
```

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →