Code Logo

Reverse Like Linked List

Published at25 Jul 2026
Operations Easy 0 views
Like0

Given an array representing a linked list, reverse the order of its elements and return the reversed array. This is equivalent to reversing a singly linked list, where each node's next pointer is redirected to point to the previous node.

For example, reversing [1, 2, 3] produces [3, 2, 1]. Reversing [5] produces [5] (a single element reversed is itself). Reversing an empty array produces []. Reversing [1, 2, 3, 4] produces [4, 3, 2, 1].

Reversing a linked list is one of the most classic linked list problems and is frequently asked in technical interviews. The array version is simpler because you can use built-in reversal methods, but the underlying concept — reversing the direction of pointers — is the same.

In a real linked list, reversal requires three pointers (previous, current, next) to iteratively redirect each node's next pointer. In array form, you can use a two-pointer swap approach: swap elements at opposite ends, moving inward until the middle is reached.

Edge cases include empty arrays (return []), single-element arrays (return the same array), and two-element arrays (simple swap). The solution works the same regardless of the values or length.

Example Input & Output

Example 1
Input
[1,2,3,4,5]
Output
[5,4,3,2,1]
Explanation

Reverse order

Algorithm Flow

Recommendation Algorithm Flow for Reverse Like Linked List

Solution Approach

Reverse the array using the built-in reverse method or a two-pointer swap.

function solution(arr) {
  return arr.slice().reverse();
}

The simplest approach uses slice() to create a copy (avoiding mutation of the input) and then reverse() to reverse it. Alternatively, you can implement the reversal manually using two pointers: initialize i = 0 and j = arr.length - 1, swap arr[i] and arr[j], then increment i and decrement j until i >= j.

function solution(arr) {
  var r = arr.slice();
  for (var i = 0, j = r.length - 1; i < j; i++, j--) {
    var t = r[i]; r[i] = r[j]; r[j] = t;
  }
  return r;
}

Time complexity is O(n), space complexity is O(n) for the copy or O(1) for in-place reversal.

Best Answers

java
class Solution {
    public int[] solution(int[] nums) {
        int[] r=nums.clone();
        for(int i=0,j=r.length-1;i<j;i++,j--){int t=r[i];r[i]=r[j];r[j]=t;}
        return r;
    }
}