List in C++

Lists are sequence containers that store elements in a non-contiguous manner. They are bidirectional and provide faster insertion and deletion operations.

The syntax of list in C++:


list <data_type> list_name;

Program to illustrate list in C++:


#include <iostream>
#include <algorithm>
#include <list>

int main()
{
        std::list<int> nums = {1, 7, 13, 8};
        for (int x : nums)
        {
                std::cout << x << '\n';
        }
}
Output
1
7
13
8

Types of List in C++

The following are the types of List in C++:

  • Single List - This is the most basic type of list where each element in the list only has a reference to the next element in the list. A single linked list only allows data to traverse in one direction.
  • Doubly Linked List - A doubly linked list is also called a two-way linked list where each element in the list has a reference to both the previous element and the next element in the list.

Advantages of using List in C++

The following are the types of List in C++:

  • Lists are dynamic data structures, they can expand and shrink in size at runtime by allocating and deallocating memory.
  • There is no memory wastage in the list because the size of the list can be increased or decreased at run time.
  • Lists has the service of insertion and deletion. After an element is inserted or deleted, there is no need to shift it, only the address in the next pointer needs to be changed.