Double a Number Represented as a Linked List

You are given the head of a non-empty linked list whose nodes hold the digits of a non-negative integer, most significant digit first, with no leading zeros except for the number 0 itself. Return the head of a linked list holding the digits of the number after doubling it.

30:00

Double a Number Represented as a Linked List
medium
Free written solution
Topics
Companies

You are given the head of a non-empty linked list whose nodes hold the digits of a non-negative integer, most significant digit first, with no leading zeros except for the number 0 itself. Return the head of a linked list holding the digits of the number after doubling it.

Example 1:
Input: {"head":[1,8,9]}
Output: [3,7,8]
Constraints:
  • The number of nodes in the list is in the range [1,104][1, 10^4].

  • 0≤Node.val≤90 \leq \text{Node.val} \leq 9

  • The input has no leading zeros, except for the number 0 itself.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[1,8,9]}

The list spells 189. Doubling it digit by digit only needs one look ahead: a digit gets +1 when the next digit is 5 or more, because that digit's double spills a carry.

■ node■ node.next (peeked)■ carry +1■ final digit
189null

Long multiplication by 2, finished digits so far

  189
×   2
  ---
  ...
Variables
VariableValue
node-
next-
DepthFunction Call
Stack empty
0/11