Open In App

How to Add an Element at the Front of a List in C++?

In C++, the STL has a doubly linked list container defined as the std::list class template inside the <list> header. It stores the sequential data in non-contiguous memory locations. In this article, we will learn how to add an element at the beginning of a list in C++ STL.

Example:

Input:
myList = {2, 3, 4, 5}

Output:
Original List Elements: 2 3 4 5
Updated List Elements: 1 2 3 4 5

Add an Element at the Beginning of the List in C++

To add an element at the beginning of a std::list in C++, we can use the std::list::push_front() method that inserts the element at the beginning of the list, hence increasing its size by one. We just need to pass the value to be added as an argument.

Syntax to std::list::push_front()

list_name.push_front(value)

Here,

C++ Program to Add an Element at the Beginning of a List

The below example demonstrates how we can use the push_front() function to add an element at the beginning of a list in C++.

// C++ program to demonstrate how we can use
// the push_front() function to add an element at the
// beginning of a list
#include <iostream>
#include <list>

using namespace std;

int main()
{
    // Create a list with some elements
    list<int> myList = { 2, 3, 4, 5 };

    // Print the original list elements
    cout << "Original List Elements:";
    for (const auto& elem : myList) {
        cout << " " << elem;
    }
    cout << endl;

    // Add an element at the beginning of the list
    myList.push_front(1);

    // Print the updated list elements
    cout << "Updated List Elements:";
    for (const auto& elem : myList) {
        cout << " " << elem;
    }
    cout << endl;

    return 0;
}

Output
Original List Elements: 2 3 4 5
Updated List Elements: 1 2 3 4 5

Time Complexity: O(1)
Auxilary Space: O(1)

Article Tags :