In the previous article, we have discussed about How to Erase Elements from a List in CPP using Iterators. Let us learn How to Reverse a List or Sub-List in Place? in C++ Program.
Lists are sequence containers that allow for the allocation of non-contiguous memory. List traversal is slower than vector traversal, but once a position is found, insertion and deletion are fast. Normally, when we talk about a List, we mean a doubly linked list. We use a forward list to implement a singly linked list.
Given a list, the task is to reverse a list or sub-list in place
Example:
Input:
stringlist ={ "hello" , "this" , "is" , "BTech" , "Geeks" }
Output:
Before reversing the list : hello this is BTech Geeks After reversing the list : Geeks BTech is this hello
Reverse a List or sub-list in place
The member function reverse() is available in std::list() to reverse the list in place
1)Reverse whole list
We can reverse the whole list using reverse() function
Below is the implementation:
#include <bits/stdc++.h> using namespace std; int main() { // Make a list and initialize it with some elements. list<string> stringlist( { "hello", "this", "is", "BTech", "Geeks" }); cout << "Before reversing the list : "; for (auto itr = stringlist.begin(); itr != stringlist.end(); ++itr) cout << *itr << " "; cout << endl; // reversing the whole list using reverse() function stringlist.reverse(); // printing the list cout << "After reversing the list : "; for (auto itr = stringlist.begin(); itr != stringlist.end(); ++itr) cout << *itr << " "; }
Output:
Before reversing the list : hello this is BTech Geeks After reversing the list : Geeks BTech is this hello
2)Reverse the sub-list
Let us reverse the first 3 elements of the list .
We can implement it using std::reverse() and std::next() functions.
Below is the implementation:
#include <bits/stdc++.h> using namespace std; int main() { // Make a list and initialize it with some elements. list<string> stringlist( { "hello", "this", "is", "BTech", "Geeks" }); cout << "Before reversing the list : "; for (auto itr = stringlist.begin(); itr != stringlist.end(); ++itr) cout << *itr << " "; cout << endl; // reversing the first 3 items of the list reverse(stringlist.begin(), next(stringlist.begin(), 3)); // printing the list cout << "After reversing the first 3 items of the list " ": "; for (auto itr = stringlist.begin(); itr != stringlist.end(); ++itr) cout << *itr << " "; }
Output:
Before reversing the list : hello this is BTech Geeks After reversing the first 3 items of the list : is this hello BTech Geeks
Related Programs:
- how to erase elements from a list in cpp using iterators
- cpp how to copy clone a stl list or sub list
- cpp how to sort a list of objects with custom comparator or lambda function
- how to iterate a map in reverse order cpp
- how to create and initialize a list of lists in python
- how to append text or lines to a file in python
- python how to find all indexes of an item in a list