Open In App

Linked List in C++

Last Updated : 11 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a linked list is a linear data structure that allows the users to store data in non-contiguous memory locations. A linked list is defined as a collection of nodes where each node consists of two members which represents its value and a next pointer which stores the address for the next node. In this article, we will learn about the linked list, its implementation, and its practical applications.

Types of Linked Lists

Following are the types of linked lists in C++:

1. Singly Linked List

The singly linked list is the simplest form of linked list in which the node contain two members data and a next pointer that stores the address of the next node. Each node is a singly linked list is connected through the next pointer and the next pointer of the last node points to NULL denoting the end of the linked list. The following diagram describes the structure of a singly linked list:

Sinlgy-Linked-List

Structure of a singly linked list

2. Doubly Linked List

The doubly linked list is the modified version of the singly linked list where each node of the doubly linked consists of three data members data ,next and prev. The prev is a pointer that stores the address of the previous node in the linked list sequence. Each node in a doubly linked list except the first and the last node is connected with each other through the prev and next pointer. The prev pointer of the first node and the next pointer of the last node points to NULL in the doubly linked list. The following diagram describes the structure of a doubly linked list:

Doubly-Linked-List

Structure of a Doubly linked list

3. Circular Linked List

The circular linked list is almost same as the singly linked list but with a small change. In a circular linked list the next pointer of the last node points to the first node of the linked list rather than pointing to NULL, this makes this data structure circular in nature which is used in various applications like media players. The following diagram describes the structure of a circular linked list:

Circular-Linked-List

Structure of a Circular linked list

4. Doubly Circular Linked List

The doubly circular linked list is a combination of a doubly linked list and a circular linked list. In a doubly circular linked list the prev pointer of the first node points to the last node and the next pointer of the last node points to the first node. The main advantage of a doubly circular linked list is that we can access the last node of the linked list in constant time through the first node. The following diagram describes the structure of a doubly circular linked list:

DoublyCircular--Linked-List

Structure of a doubly circular linked list

Implementation of Linked List in C++

To implement a linked list in C++ we can follow the below approach:

Approach:

  • Define a structure Node having two members data and a next pointer. The data will store the value of the node and the next pointer will store the address of the next node in the sequence. For doubly linked list you will have to add an addition pointer prev that will store the address of the prev node in the sequence.
  • Define a class LinkedList consisting of all the member functions for the LinkedList and a head pointer that will store the reference of a particular linked list.
  • Initialize the head to NULL as the linked list is empty initially.
  • Implement basic functions like insertAtBeginning, insertAtEnd, deleteFromBeginning, deleteFromEnd that will manipulate the elements of the linked list.

Representation of a Node in the Linked List

Each node of the linked list will be represented as a structure having two members data and next where:

  • Data: Represents the value stored in the node.
  • Next Pointer: Stores the reference to the next node in the sequence.
struct Node {    
int data;
Node* next;
};

Note: Add another data member Node * prev in the structure for doubly linked lists.

Basic Operations of a Linked List

Following are some basic operations which are required to manipulate the nodes of a linked list:

OperationDescriptionTime ComplexitySpace Complexity
insertAtBeginningAttaches a new node at the start of the linked list.O(1)O(1)
insertAtEndAttaches a new node at the end of the linked list.O(n)O(1)
insertAtPositionAttaches a new node at a specific position in the linked list.O(n)O(1)
deleteFromBeginningRemoves the Head of the linked list and updates the Head to the next nodeO(1)O(1)
deleteFromEndRemoves the node present at the end of the linked list.O(n)O(1)
deleteFromPositionRemoves a node from a given position of the linked list.O(n)O(1)
DisplayPrints all the values of the nodes present in the linked list.O(n)O(1)

Note: Here n denotes the number of nodes in the linked list.

Now let’s learn how we can implement these basic functions of linked list in C++:

Algorithm for insertAtBeginning Implementation

  1. Create a new Node
  2. Point the new Node’s next pointer to the current head.
  3. Update the head of the linked list as the new node.
Insert-At-First-Linked-List

Inserting a node at the first of the linked list

Algorithm for insertAtEnd Implementation

  1. Create a new Node
  2. If the linked list is empty, update the head as the new node.
  3. Otherwise traverse till the last node of the linked list.
  4. Update the next pointer of the last node from NULL to new node.
Insert-At-End-Linked-List

Inserting a node at the end of the linked list

Algorithm for insertAtPosition Implementation

  1. Check if the provided position by the user is a valid poistion.
  2. Create a new node.
  3. Find the node at position -1.
  4. Update the next pointer of the new node to the next pointer of the current node.
  5. Update the next pointer of the current node to new node.
Insert-After-Position-Linked-List

Inserting a node after the second position in the linked list

Algorithm for deleteFromBeginning Implementation

  1. Check whether the Head of the linked list is not NULL. If Head is equal to NULL return as the linked list is empty, there is no node present for deletion.
  2. Store the head of the linked list in a temp pointer.
  3. Update the head of the linked list to next node.
  4. Delete the temporary node stored in the temp pointer.
Delete-First-Position-Linked-List

Deleting the first node of the linked list

Algorithm for deleteFromEnd Implementation

  1. Verify whether the linked is empty or not before deletion.
  2. If the linked list has only one node, delete head and set head to NULL.
  3. Traverse till the second last node of the linked list.
  4. Store the last node of the linked list in a temp pointer.
  5. Pointer the next pointer of the second last node to NULL.
  6. Delete the node represented by the temp pointer.
Delete-Last-Position-Linked-List

Deleting the last node of the linked list

Algorithm for deleteFromPosition Implementation

  1. Check if the provided postion by the users is a valid position in the linked list or not.
  2. Find the node at position -1.
  3. Save node to be deleted in a temp pointer.
  4. Set the next pointer of the current node to the next pointer of the node to be deleted.
  5. Set the next pointer of temp to NULL.
  6. Delete the node represented by temp pointer.
Delete-From-Middle-Linked-List

Deleting the node present at the second position in the linked list

Algorithm for Display Implementation

  1. Check if the Head pointer of the linked list is not equal to NULL.
  2. Set a temp pointer to the Head of the linked list.
  3. Until temp becomes null:
    1. Print temp->data
    2. Move temp to the next node.

C++ Program for Implementation of Linked List

The following program illustrates how we can implement a singly linked list data structure in C++:

C++
// C++ Program for Implementation of linked list
#include <iostream>
using namespace std;

// Structure for a node in the linked list
struct Node {
    int data;  
    Node* next; 
};

// Define the linked list class
class LinkedList {
     // Pointer to the first node in the list
    Node* head;

public:
    // Constructor initializes head to NULL
    LinkedList() : head(NULL) {}

    // Function to Insert a new node at the beginning of the list
    void insertAtBeginning(int value) {
        Node* newNode = new Node(); 
        newNode->data = value;      
        newNode->next = head;      
        head = newNode;            
    }

    // Function Insert a new node at the end of the list
    void insertAtEnd(int value) {
        Node* newNode = new Node(); 
        newNode->data = value;      
        newNode->next = NULL;       

        // If the list is empty, update the head to the new node
        if (!head) {
            head = newNode;
            return;
        }

        // Traverse to the last node
        Node* temp = head;
        while (temp->next) {
            temp = temp->next;
        }

        // Update the last node's next to the new node
        temp->next = newNode;
    }

    // Function to Insert a new node at a specific position in the list
    void insertAtPosition(int value, int position) {
        if (position < 1) {
            cout << "Position should be >= 1." << endl;
            return;
        }

        if (position == 1) {
            insertAtBeginning(value);
            return;
        }

        Node* newNode = new Node(); 
        newNode->data = value;     

        // Traverse to the node before the desired position
        Node* temp = head;
        for (int i = 1; i < position - 1 && temp; ++i) {
            temp = temp->next;
        }

        // If the position is out of range, print an error message
        if (!temp) {
            cout << "Position out of range." << endl;
            delete newNode;
            return;
        }

        // Insert the new node at the desired position
        newNode->next = temp->next;
        temp->next = newNode;
    }

    // Function to Delete the first node of the list
    void deleteFromBeginning() {
        if (!head) {
            cout << "List is empty." << endl;
            return;
        }

        Node* temp = head; 
        head = head->next; 
        delete temp;      
    }

    // Function to Delete the last node of the list
    void deleteFromEnd() {
        if (!head) {
            cout << "List is empty." << endl;
            return;
        }

        if (!head->next) {
            delete head;   
            head = NULL;   
            return;
        }

        // Traverse to the second-to-last node
        Node* temp = head;
        while (temp->next->next) {
            temp = temp->next;
        }
        
        //  Delete the last node
        delete temp->next; 
        // Set the second-to-last node's next to NULL
        temp->next = NULL; 
    }

    // Function to Delete a node at a specific position in the list
    void deleteFromPosition(int position) {
        if (position < 1) {
            cout << "Position should be >= 1." << endl;
            return;
        }

        if (position == 1) {
            deleteFromBeginning();
            return;
        }

        Node* temp = head;
        for (int i = 1; i < position - 1 && temp; ++i) {
            temp = temp->next;
        }

        if (!temp || !temp->next) {
            cout << "Position out of range." << endl;
            return;
        }
        // Save the node to be deleted
        Node* nodeToDelete = temp->next; 
        // Update the next pointer
        temp->next = temp->next->next;   
         // Delete the node
        delete nodeToDelete;            
    }

    // Function to print the nodes of  the linked list
    void display() {
        if (!head) {
            cout << "List is empty." << endl;
            return;
        }

        Node* temp = head;
        while (temp) {
            cout << temp->data << " -> "; 
            temp = temp->next;
        }
        cout << "NULL" << endl; 
    }
};

int main() {
    // Initialize a new linked list
    LinkedList list1;

    // Insert elements at the end
    list1.insertAtEnd(10);
    list1.insertAtEnd(20);

    // Insert element at the beginning
    list1.insertAtBeginning(5);

    // Insert element at a specific position
    list1.insertAtPosition(15, 3);

    cout << "Linked list after insertions: ";
    list1.display();

    // Delete element from the beginning
    list1.deleteFromBeginning();
    cout << "Linked list after deleting from beginning: ";
    list1.display();

    // Delete element from the end
    list1.deleteFromEnd();
    cout << "Linked list after deleting from end: ";
    list1.display();

    // Delete element from a specific position
    list1.deleteFromPosition(2);
    cout << "Linked list after deleting from position 2: ";
    list1.display();

    return 0;
}


Output

Linked list after insertions: 5 -> 10 -> 15 -> 20 -> NULL
Linked list after deleting from beginning: 10 -> 15 -> 20 -> NULL
Linked list after deleting from end: 10 -> 15 -> NULL
Linked list after deleting from position 2: 10 -> NULL

Note: You can easily implement the other types of linked lists with some minor changes in the above code.

Applications of Linked Lists

Following are some common applications of the linked list data structure:

Related Articles

Following are some of the articles that you can also read to improve your understanding about the linked list data structure:



Similar Reads

C++ Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6, m = 2, n = 5, k = 2 Output: 1-&gt;4-&gt;5-&gt;2-&gt;3-&gt;6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
C++ Program For Detecting Loop In A Linked List
Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. The following are different ways of doing this. Solution 1: Hashing Approach: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false, and if the next of the curre
11 min read
C++ Program For Moving Last Element To Front Of A Given Linked List
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1-&gt;2-&gt;3-&gt;4-&gt;5, then the function should change the list to 5-&gt;1-&gt;2-&gt;3-&gt;4. Algorithm: Traverse the list till the last node. Use two pointers: one to store the address of the last node and the other
3 min read
C++ Program For Deleting A Given Node In Linked List Under Given Constraints
Given a Singly Linked List, write a function to delete a given node. Your function must follow the following constraints: It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to the head node is not global.It should not return a pointer to the head node.It should not accept
4 min read
Number of connected components in a doubly linked list
Given a doubly linked list ‘L’ and an array ‘refArr’ of references to the nodes of the doubly linked list ‘L’. Array 'refArr' does not contain any duplicate references and the references are not ORDERED. m &lt;= total no. of nodes in the doubly linked list where m = size of the reference array. The task is to find the total number of connected comp
15+ min read
Check if linked list is sorted (Iterative and Recursive)
Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? Examples : Input : 8 -&gt; 7 -&gt; 5 -&gt; 2 -&gt; 1 Output : Yes Explanation : In given linked list, starting from head, 8 &gt; 7 &gt; 5 &gt; 2 &gt; 1. So, it is sorted in reverse order Input : 24 -&gt; 12 -&gt; 9 -&gt; 11 -&gt; 8 -&gt; 2 Output : N
8 min read
C++ Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14, x = 12, y = 20 Output:
5 min read
Delete every Kth node from circular linked list
Delete every kth node from a circular linked list until only one node is left. Also, print the intermediate lists. Examples: Input : n=4, k=2, list = 1-&gt;2-&gt;3-&gt;4 Output : 1-&gt;2-&gt;3-&gt;4-&gt;1 1-&gt;2-&gt;4-&gt;1 2-&gt;4-&gt;2 2-&gt;2 Input : n=9, k=4, list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;9 Output : 1-&gt;2-&gt;3-&gt;4
13 min read
Replace each node with its Surpasser Count in Linked List
Given LinkedList, replace each node's value with its surpasser count. That is the count of elements which are greater towards its right. Examples: Input : 10-&gt;12-&gt;5-&gt;40-&gt;21-&gt;70-&gt;1-&gt;49-&gt;37-&gt;NULL Output : 6-&gt;5-&gt;5-&gt;2-&gt;3-&gt;0-&gt;2-&gt;0-&gt;0-&gt;NULL Explanation : Element in the first node is 10 and the number
12 min read
Insert N elements in a Linked List one after other at middle position
Given an array of N elements. The task is to insert the given elements at the middle position in the linked list one after another. Each insert operation should take O(1) time complexity.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 -&gt; 3 -&gt; 5 -&gt; 4 -&gt; 2 -&gt; NULL 1 -&gt; NULL 1 -&gt; 2 -&gt; NULL 1 -&gt; 3 -&gt; 2 -&gt; NULL 1 -
10 min read
Practice Tags :