The list::push_front() is a built-in function in C++ STL which is used to insert an element at the front of a list container just before the current top element. This function also increases the size of the container by 1.
Syntax
list_name.push_front(dataType value)
- Parameters: value- The element to be inserted at the front of the list.
- Return Value: This function does not return any value.
Example: The following program demonstrates the use of list::push_front():
#include <iostream>
#include <list>
using namespace std;
int main()
{
// Creating a list
list<int> demoList;
// Adding elements using push_back()
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
// Printing initial list
cout << "Initial List: ";
for (int val : demoList)
cout << val << " ";
// Inserting element at the front
demoList.push_front(5);
// Printing updated list
cout << "\n\nList after push_front(): ";
for (int val : demoList)
cout << val << " ";
return 0;
}
Output
Initial List: 10 20 30 40 List after push_front(): 5 10 20 30 40
Explanation:
- initially, elements 10, 20, 30, 40 are inserted at the end using push_back().
- push_front(5) call inserts 5 at the beginning.
- std::list is a doubly linked list, no shifting of elements occurs.
- new element becomes the first node of the list.