Open In App

How to Remove an Element from Beginning of List in C++?

In C++, lists are sequence containers provided by the STL library, that allow the users to store data in non-contiguous memory locations. Lists are similar to vectors but lists allow constant time insert and delete operations from both ends. In this article, we will learn how to remove an element from the beginning of a list in C++.

Example

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

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

Remove an Element from Beginning of List in C++

To remove an element from the beginning of a std::list in C++, the simplest way is to use the std::list::pop_front() method provided by the list container. This function removes the first element of the list in constant time.

Syntax

list_name.pop_front()

C++ Program to Remove an Element from the Beginning of a List

The following program illustrates how we can remove an element from the beginning of a list in C++:

// C++ program to illustrate how to remove an element from
// the beginning of a list
#include <iostream>
#include <list>
using namespace std;

int main()
{
    list<int> l = { 1, 2, 3, 4, 5 };

    // Print the original list
    cout << "Original List: ";
    for (int x : l) {
        cout << x << " ";
    }
    cout << endl;

    // Remove the first element from the list
    l.pop_front();

    // Print the modified list
    cout << "Updated List: ";
    for (int x : l) {
        cout << x << " ";
    }

    return 0;
}

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

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



Article Tags :