How to Remove an Element from the End of a List in C++?
In C++, lists are data structures that allow us to store data of the same type in non-contiguous memory locations. In this article, we will learn how to remove an element from the end of a list in C++.
Example
Input: myList={10,20,30,40,50} Output: List Elements: 10 20 30 40
Delete the Last Element from a List in C++
To remove an element from the end of a std::list in C++, we can use the std::list::pop_back() function that removes the last element from a list in constant time.
Syntax of std::list::pop_back()
list_name.pop_back()
C++ Program to Remove an Element from the End of a List
The following program illustrates how we can remove an element from the end of a list using the pop_back() method in C++.
// C++ Program to how we can remove an element from the end
// of a list using the pop_back() method
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Initializing a list
list<int> l1 = { 10, 20, 30, 40, 50 };
// Printing the original list
cout << "Original List: ";
for (int element : l1) {
cout << element << " ";
}
cout << endl;
// Removing the last element of the list using pop_back
l1.pop_back();
// Printing the list after removing the last element
cout << "List after removing the last element: ";
for (int element : l1) {
cout << element << " ";
}
return 0;
}
Output
Original List: 10 20 30 40 50 List after removing the last element: 10 20 30 40
Time Complexity: O(1)
Auxiliary Space: O(1)
Contact Us