Idiom #19 Reverse a list
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
- Ada
- C
- Caml
- Clojure
- C++
- C#
- D
- D
- Elixir
- Erlang
- Fortran
- Go
- Go
- Go
- Groovy
- Haskell
- JS
- Java
- Java
- Java
- Java
- Java
- Kotlin
- Kotlin
- Kotlin
- Lisp
- Lua
- Lua
- Lua
- Obj-C
- PHP
- Pascal
- Pascal
- Perl
- Prolog
- Python
- Python
- Python
- Ruby
- Rust
- Rust
- Scala
- Scheme
- Smalltalk
- VB
func reverse[T any](x []T) {
for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
x[i], x[j] = x[j], x[i]
}
}
This generic function works for any type parameter T.
It operates in-place.
It operates in-place.
x = x.reverse();
note that Array.prototype.reverse() not only returns the reversed array, it works in place!
int i, m = x.size(), n = m-- / 2;
for (i = 0; i < n; ++i) swap(x, i, m - i);
static <T> void reverse(List<T> x){
int n = x.size();
for(int i=0;i<n/2;i++){
T tmp = x.get(i);
x.set(i, x.get(n-i-1));
x.set(n-i-1, tmp);
}
}
This method works for lists of any element type T .
In case of an odd number of elements, the central element doesn't need to be swapped.
In case of an odd number of elements, the central element doesn't need to be swapped.
val reversedView = x.asReversed()
Returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.
rev = {}
for i=#x, 1, -1 do
rev[#rev+1] = x[i]
end
-- in-situ reversal
function reverse(t)
local n = #t
local i = 1
for i = 1, n do
t[i],t[n] = t[n],t[i]
n = n - 1
end
end
my @list = ('words', 'of', 'list', 'a', 'reverse');
my @reversed = reverse @list;
reverse is a built-in function. Given an array, it will reverse it. Given a string, it will return a string with the letters reversed.
programming-idioms.org