In C++, std::list::reverse() reverses the order of all elements in a std::list. The first element becomes the last one, the second becomes the second to last, and so on.
It changes the links of the nodes, so no element is copied or moved in memory. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call reverse with empty brackets on the list that you want to flip.
C++
l.reverse(); // 1 2 3 -> 3 2 1
Call
What it does
l.reverse()
Reverses the list in place. The list keeps the same elements and the same size.
std::reverse(l.begin(), l.end()) also works on a list, but the member function is made for lists and relinks nodes instead of swapping values.
Library declarations
C++
void reverse() noexcept;
Parameters
Parameter
Description
None
reverse() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Nothing
reverse() returns void. The list is changed in place.
C++ Examples
Example 1 — reverse() Flips the Order
Reverse a list of four numbers in place.
C++
#include <iostream>
#include <list>
int main() {
std::list<int> l = {1, 2, 3, 4};
l.reverse();
for (int n : l) {
std::cout << n << ' ';
}
std::cout << '\n';
std::cout << "front: " << l.front() << ", back: " << l.back() << '\n';
return 0;
}
Output
4 3 2 1
front: 4, back: 1
How It Works
The list starts as 1 2 3 4, with 1 first and 4 last.
reverse() swaps the previous and next links of every node, so the chain is read the other way round.
The loop prints 4 3 2 1. front() is now 4 and back() is now 1.
Example 2 — reverse() and Iterators
An iterator keeps pointing at its element, even though the element changes place.
C++
#include <iostream>
#include <iterator>
#include <list>
int main() {
std::list<int> l = {1, 2, 3};
auto it = l.begin(); // points at 1
l.reverse();
std::cout << std::boolalpha;
std::cout << "*it: " << *it << '\n';
std::cout << "it is now last: " << (it == std::prev(l.end())) << '\n';
return 0;
}
Output
*it: 1
it is now last: true
How It Works
it points at the node that holds 1, the first node.
reverse() does not create new nodes. It only changes how they are linked, so it still points at the same node.
That node is now at the end, so it equals std::prev(l.end()), while *it is still 1.
Example 3 — reverse() to Check a Palindrome
A palindrome reads the same forwards and backwards. Copy the list, reverse the copy, and compare.