Open In App

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

In C++, the Standard Template Library (STL) has a doubly-linked list container, known as std::list that offers various functions to manipulate elements. In this article, we will learn how to add an element at the end of a list in C++ STL.

Example:

Input:
myList = {1, 2, 3};

Output:
List after Element Added: 1 2 3 4

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

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

Syntax to Add an Element at the End of a List in C++

list_name.push_back(value)

Here,

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

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

// C++ Program to illustrate how to add an element at the
// end of a list
#include <iostream>
#include <list>
using namespace std;

int main()
{

    // Creating a list
    list<int> myList = { 1, 2, 3 };

    // Printing the original list
    cout << "Original List:";
    for (int num : myList) {
        cout << " " << num;
    }
    cout << endl;

    // Adding an element at the end of the list
    myList.push_back(4);

    // Printing the list after adding the element
    cout << "List after Element Added:";
    for (int num : myList) {
        cout << " " << num;
    }
    cout << endl;

    return 0;
}

Output
Original List: 1 2 3
List after Element Added: 1 2 3 4

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



Article Tags :