Linked List Reverse Order using C++ STL

In this c++ tutorial, we are going to discuss how to print a linked list in reverse order using C++ STL library.

Here we will learn the following things:

  • List in C++
  • Insert element in a list
  • Remove element from a list
  • Check if a list is empty or not
  • Reverse a Linked List in c++

What is List?

List is a sequence container in C++ STL which allows storing elements in a non-contiguous memory location. List in C++ STL is an implementation of a doubly linked list to implement a singly linked list in STL forward list is used.

How to insert element in a List?

To insert element at the back of list we use list_name.push_back ( element )  in STL.

Example:

list<int>l;

l.push_back(1);

To insert an element at front of list we use list_name.push_front ( element ) in STL.

Example :

list<int>l;

l.push_front ( element );

How to remove an element from List

To remove an element from back of list we use list_name.pop_back().

Example :

list<int>l;
l.pop_back();

To remove an element from front of list we use list_name.pop_front().

Example :

list<int>l;

l.pop_front();

How to check whether a list is empty or not

In C++ STL to check whether a list is empty or not we use list_name.empty() . If the list is empty it will return 1  otherwise 0.

Example

list<int>l;
while(!l.empty() )
{
cout<<l.back()<<endl;
}

How to print an element of List?

In C++STL to print an element of list, if we have to print an element from back of list we use list_name.back() and if we have to print an element front of list we use list_name.front().

Example :-

list<int>l;

l.back();

l.front();

Reverse a linked list in C++

Algorithm

  • Declare a list using list<data_type>list_name.
  • Insert elements in list using list_name.push_back(value).
  • Print the elements from back of list using list_name.back() after printing last element each time remove that element from list using list_name.pop_back().
  • Proceed the above step till the list does not become empty to check whether list is empty using list_name.empty().

C++ code to print a linked list in reverse order using List

#include<bits/stdc++.h>
using namespace std;

   int main()
 {
     list<int>l;
     
     l.push_back(1);
     l.push_back(2);
     l.push_back(3);
     
    
     
       while(!l.empty())
     {

             cout<<l.back()<<" ";
               l.pop_back();
     }
     
 }

INPUT

1 2 3

OUTPUT

3 2 1

Also, learn,

Leave a Reply

Your email address will not be published. Required fields are marked *