How to Traverse a List with reverse_iterator in C++?
In C++, lists are containers that allow users to store data in non-contiguous memory locations. List provides reverse iterators that make it easy to traverse the list in reverse order. In this article, we will learn how to traverse a list with reverse_iterator in C++.
Example
Input: myList = {10,20,30,40,50} Output: 50 40 30 20 10
Iteratore a List with reverse_iterator in C++
Reverse iterators in C++ are used to traverse the list in a backward direction starting from the end of the list towards the beginning. The std::list class template has two member functions that provide the reverse iterators:
- list::rbegin(): Returns the reverse iterator pointing to the last element in the list.
- list::rend(): Returns a reverse iterator pointing to the element just before the first element in the list.
C++ Program to Traverse a List with reverse_iterator
The following program illustrates how we can traverse a list using a reverse_iterator in C++:
// C++ Program to illustrate how to traverse a list with
// reverse_iterator
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Initializing a List
list<int> l = { 10, 20, 30, 40, 50 };
// Declare the reverse iterator of the list
list<int>::reverse_iterator it;
// Traverse the elements of the list using the
// reverse_iterator
for (it = l.rbegin(); it != l.rend(); it++) {
cout << *it << " ";
}
return 0;
}
Output
50 40 30 20 10
Time Complexity: O(N) where N is the size of the list.
Auxiliary Space: O(1)
Contact Us