Problem 585
Insert Greatest Common Divisors in a Linked List
Medium · 20 pts · Linked List, Math
Problem
Between every pair of adjacent nodes of a linked list, insert a new node whose value is the greatest common divisor of those two nodes. The new nodes are only inserted between original neighbours, never between a new node and an old one. Print the resulting list. Walk the list once, and after each original node (except the last) insert gcd(node, next node) and then jump past it.
Input
The first line contains N, the number of nodes. The second line contains the N node values from head to tail.
Output
Print the resulting list from head to tail, separated by spaces.
Constraints
1 <= N <= 5000; 1 <= value <= 1000
Example input
4 18 6 10 3
Example output
18 6 6 2 10 1 3
Explanation
For 18 6 10 3, the inserted values are gcd(18, 6) = 6, gcd(6, 10) = 2 and gcd(10, 3) = 1. The result is 18 6 6 2 10 1 3.