Open In App
Related Articles

list push_front() function in C++ STL

Improve Article
Improve
Save Article
Save
Like Article
Like

The list::push_front() is a built-in function in C++ STL which is used to insert an element at the front of a list container just before the current top element. This function also increases the size of the container by 1.

Syntax

list_name.push_front(dataType value)

Parameters

  • This function accepts a single parameter value. This parameter represents the element which is needed to be inserted at the front of the list container.

Return Value

  • This function does not return anything.

Example

The below program illustrate the list::push_front() function in C++ STL.

C++




// CPP program to illustrate the
// list::push_front() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // Creating a list
    list<int> demoList;
 
    // Adding elements to the list
    // using push_back()
    demoList.push_back(10);
    demoList.push_back(20);
    demoList.push_back(30);
    demoList.push_back(40);
 
    // Initial List:
    cout << "Initial List: ";
    for (auto itr = demoList.begin(); itr != demoList.end();
         itr++)
        cout << *itr << " ";
 
    // Adding elements to the front of List
    // using push_front
    demoList.push_front(5);
 
    // List after adding elements to front
    cout
        << "\n\nList after adding elements to the front:\n";
    for (auto itr = demoList.begin(); itr != demoList.end();
         itr++)
        cout << *itr << " ";
 
    return 0;
}


Output

Initial List: 10 20 30 40 

List after adding elements to the front:
5 10 20 30 40 

Time Complexity: O(n)
Auxiliary Space: O(1)

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 30 May, 2023
Like Article
Save Article
Similar Reads