This article explores different ways to in-place reverse a list in Kotlin.

The conversion should be done in-place, i.e., without using any auxiliary space by overwriting the existing elements of the specified list.

1. Using Collections.reverse() function

To in-place reverse the order of the elements in a list, you can use the Collections.reverse() function. It takes the list whose elements are to be reversed.

Download Code

2. Using reversed() function

You can also use the native reversed() function to reverse a list, but the conversion won’t be in-place, and it creates a new list.

Download Code

 
If you just need the view of the list in reverse order, you can get one using the asReversed() function.

Download Code

2. Using add() with removeLast() function

Another plausible way to in-place reverse a list is to reorder the elements within the list. We can do this by removing an element from the end of the list and insert it into the very beginning, one at a time, using a for-loop.

Download Code

3. Using Recursion

Finally, you can use recursion to in-place reverse a list. Here’s a recursive solution:

Download Code

That’s all about in-place reversing a list in Kotlin.