Menu
CoddyTech

Reverse Linked List

You get a singly linked list stored in the array next: node i 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.

Reverse the list by turning every link around, so the old last node becomes the head and node 0 becomes the last node, linking to -1. Return the updated next array, which has the same length as the input.

Function

reverseList(next: integer-array) → integer-array
nextinteger-array
the index of the node each node links to, or -1 for the last node
Returnsinteger-array
the next array of the reversed list

Constraints

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

Examples

Input
next = [1, 2, 3, -1]
Output
[-1, 0, 1, 2]
Explanation
The list is 0 → 1 → 2 → 3. Reversed it is 3 → 2 → 1 → 0, so node 3 links to 2, node 2 to 1, node 1 to 0, and node 0 to -1.

lock icon+11 hidden tests on Submit

challenge icon

Follow-up

Can you reverse only the part of the list between position left and position right, and leave the nodes before and after it where they are?

Reset code
def reverseList(next):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

next = [1, 2, 3, -1]

Expected

[-1, 0, 1, 2]