C++ program to interchange first and last elements in a list

In this tutorial, we will see how to interchange the first and last elements in a container list in C++.

Here we need to note that the list uses a doubly linked list than the forward list which is implemented as singly-linked lists. This gives us more options to traverse through the list.

Lists are containers allowing non-contiguous allocation of memory. As compared to vectors, list has slower traversal, but once the position has been found, insertion and deletion operations are quick.

In the given below code snippet, we use various inbuilt functions for list containers to ease our task.

An iterator to the front of this list is given by list_name.begin() and to the end is given by list_name.end().

We also use the pre-defined functions for list so as to push elements to a list and also pop them at both starting and ending positions.

#include <iostream> 
#include <list> 
using namespace std; 
  
int main() 
{ 
    // declaration of list container with 5 elements 
    list<int> mylist{ 1, 2, 3, 4, 5 }; 
  
    auto it = mylist.begin(); 
        int a =*it;
    auto it1=mylist.end();
    	int b=*it1;
    	mylist.pop_front();
    	mylist.pop_back();
    	mylist.push_back(a);
    	mylist.push_front(b);

    //to print the interchanged list 	
    for(auto itr=mylist.begin();itr!=mylist.end();itr++)
    	{
    		cout<<*itr<<" ";
    	}
    return 0; 
}

Sample Output:

5 2 3 4 1

Also Read: How to Reverse the Elements of an Array in C++

Leave a Reply

Your email address will not be published.