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
Returns (int[]) [5,4,3,2,1]

Example 2

Input
nodes (int[]) = [1,2]
size (int) = 2
Returns (int[]) [2,1]

Example 3

Input
nodes (int[]) = [1]
size (int) = 1
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.