Menu
CoddyTech

Reorder List

You get a singly linked list stored in two arrays of the same length. Node i holds the value values[i] and links to node next[i], -1 ends the list, and the head is node 0. The nodes are not stored in list order, so follow the links.

Call the nodes in list order L0, L1, ..., Lk. Reorder the list so it runs L0, Lk, L1, Lk-1, L2, Lk-2, ...: the first node, then the last, then the second, then the second to last, and so on. Return the values in that new order.

Function

reorderList(next: integer-array, values: integer-array) → integer-array
nextinteger-array
the index of the node each node links to, or -1 for the last node
valuesinteger-array
the value held by each node
Returnsinteger-array
the values in the reordered list order

Constraints

  • 1 ≤ n ≤ 4000, where n is the length of next and of values.
  • -1000 ≤ values[i] ≤ 1000
  • Each next[i] is -1 or a node index from 0 to n-1.
  • Starting at node 0, the list visits every node exactly once and then reaches -1. There is no cycle.

Examples

Input
next = [3, 4, -1, 1, 2]values = [1, 3, 5, 2, 4]
Output
[1, 5, 2, 4, 3]
Explanation
Following the links from node 0, the list reads 1, 2, 3, 4, 5. First, last, second and second to last give 1, 5, 2, 4, and the middle value 3 comes last.
challenge icon

Follow-up

Can you reorder the links themselves with O(1) extra memory?

Reset code
def reorderList(next, values):
    # Write code here

Test #1

Test #2

Test #3

Arguments

next = [3, 4, -1, 1, 2]
values = [1, 3, 5, 2, 4]

Expected Output

[1, 5, 2, 4, 3]