Logo

Programming-Idioms

Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
with Ada.Containers.Vectors;
use Ada.Containers;
X.Reverse_Elements;
int *p1 = x;
int *p2 = x + N-1;

while (p1 < p2)
{
    int temp = *p1;
    *(p1++) = *p2;
    *(p2--) = temp;
}
List.rev x
(reverse x)
#include <algorithm>
std::reverse(begin(x), end(x));
System.Collections.Generic;
x.Reverse();
import std.algorithm;
reverse(x);
import std.range;
auto y = x.retro;
x = x.reversed.toList();
x = Enum.reverse(x)
lists:reverse(List)
  a = a(ubound(a,dim=1)::-1)
for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
	x[i], x[j] = x[j], x[i]
}
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]
	}
}
x = x.reverse()
reverse x
x = x.reverse();
import java.util.List;
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);
	}
}
import java.util.Collections;
Collections.reverse(x);
import java.util.Collections;
Collections.reverse(x);
x.reverse()
val reversedView = x.asReversed()
x = x.reversed()
(reverse x)
function array_reverse(x)
  local n, m = #x, #x/2
  for i=1, m do
    x[i], x[n-i+1] = x[n-i+1], x[i]
  end
  return x
end
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
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end
x = rev
@import Foundation;
x.reverseObjectEnumerator.allObjects
$x = array_reverse($x, true);
var n,i: integer;
	tmp:TElement;
[...]
n:= length(x);
for i := 0 to (n div 2)-1 do
	begin
		tmp := x[i];
		x[i] := x[n-i-1];
		x[n-i-1] := tmp;
	end;
var n,i: integer;
[...]
n:= length(x);
setlength(x, n+1);
for i := 0 to (n div 2)-1 do
	begin
		x[n] := x[i];
		x[i] := x[n-i-1];
		x[n-i-1] := x[n];
	end;
setlength(x, n);
my @list = ('words', 'of', 'list', 'a', 'reverse');
my @reversed = reverse @list;
x = reversed(x)
x.reverse()
y = x[::-1]
x.reverse!
x.reverse();
let y: Vec<_> = x.into_iter().rev().collect();
x = x.reverse
(reverse x)
X reversed.
Dim ItemList As New List(Of String)(New String() {"one", "two", "three"})
ItemList.Reverse()
For Each item In ItemList
    Console.WriteLine(item)
Next