Reversing a List in C++
To reverse a std::list in C++, we can use the std::list::reverse() member function. This function reverses the order of the elements in-place in the list container.
Syntax to Reverse a std::list in C++
list_name.reverse()
C++ Program to Reverse a List
The below example demonstrates the use of the list::reverse() function to reverse a std::list in C++ STL.
// C++ program to reverse a list
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Creating a list of integers
list<int> nums = { 10, 20, 30, 40, 50 };
// Reversing the list
nums.reverse();
// Printing the list after reversal
cout << "Reversed List: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
Output
Reversed List: 50 40 30 20 10
Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(1)
How to Reverse a List in C++ STL?
In C++, std::list
is a sequence container that allows non-contiguous memory allocation. As such, it is a doubly linked list that can be traversed in both directions. In this article, we will learn how to reverse a list in C++.
Example:
Input: myList = {10, 20, 30, 40, 50}; Output: Reversed List: 50 40 30 20 10