Open In App

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

Last Updated : 04 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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,

  • list_name denotes the name of the list where the element will be added.
  • value is the element that will be added to the beginning of the list.

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++
// 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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads