Problem 583
Double a Number Represented as a Linked List
Medium · 20 pts · Linked List, Math
Problem
A non-negative number is stored in a linked list, one digit per node, with the most significant digit at the head and no leading zeros (except the number 0 itself). Double the number and print the digits of the result from head to tail. The number can have thousands of digits. Process the digits from the tail to keep the carry, or notice that a node gains a carry exactly when the next digit is 5 or more, which allows a single pass from the head.
Input
The first line contains N, the number of digits. The second line contains the N digits from head to tail.
Output
Print the digits of the doubled number from head to tail, separated by spaces.
Constraints
1 <= N <= 10000; each digit is between 0 and 9; no leading zeros unless the number is 0
Example input
3 1 8 9
Example output
3 7 8
Explanation
The list 1 8 9 stands for 189. Doubling gives 378, so the answer is the list 3 7 8.