Learner Level

Implement the reverseLinkedListInterview method that returns linked list values after reversing the list.

The linked list is provided as an integer array named nodes, where each value represents one node from head to tail.

Your task is to reverse the linked list and return the values from the new head to the new tail.

For example, [1,2,3,4,5] should become [5,4,3,2,1].

Example 1
Input:
nodes (int[]) = [1,2,3,4,5]
size (int) = 5
Return:
(int[]) [5,4,3,2,1]
Example 2
Input:
nodes (int[]) = [1,2]
size (int) = 2
Return:
(int[]) [2,1]
Example 3
Input:
nodes (int[]) = [1]
size (int) = 1
Return:
(int[]) [1]

In a real linked list, this problem is solved by changing each node pointer so that it points to the previous node instead of the next node.

Because this problem represents the linked list as an array, we can return the values in reverse order. A two-pointer approach swaps the first and last values, then moves inward until the whole sequence is reversed.

Pseudocode:

function reverseLinkedListInterview(nodes, size):
    left = 0
    right = size - 1
    while left < right:
        swap nodes[left] and nodes[right]
        left++
        right--
    return nodes
Run your code to see the result.