Open In App

How to Reverse a List in C++ STL?

Last Updated : 21 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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++
// 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads