The Wayback Machine - https://web.archive.org/web/20240708032433/https://www.geeksforgeeks.org/linked-list-of-linked-list/
Open In App

Linked List of Linked List

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

Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the basics of Linked List of Linked List, how to create Linked List of Linked List, its applications, advantages and disadvantages.

Linked-List-of-Linked-List

Representation of Linked List of Linked List:

A Linked List of Linked list is represented by a pointer to the first node of the linked lists. Similar to the linked list, the first node is called the head. If the multilevel linked list is empty, then the value of head is NULL. Each node in a list consists of at least three parts:

  • Data.
  • Pointer to the next node.
  • Pointer to the child node.

Each node of a multilevel linked list is represented as:

class Node
{
        public:
                 int data;
                 Node *next;
                 Node *child;
 };

Creating a Linked List of Linked Lists:

Below is the implementation of the multilevel linked list

C++
#include <iostream>
#include <vector>
using namespace std;

// Class to represent the node of the linked list
class Node {
public:
    int data;
    Node* next;
    Node* child;

    Node()
    {
        data = 0;
        next = nullptr;
        child = nullptr;
    }
};

// A function to create a linked list
// with n(size) Nodes returns head pointer
Node* createList(vector<int>& arr, int n)
{
    Node* head = nullptr;
    Node* tmp = nullptr;

    // Traversing the passed array
    for (int i = 0; i < n; i++) {

        // Creating a Node if the list
        // is empty
        if (head == nullptr) {
            tmp = head = new Node();
        }
        else {
            tmp->next = new Node();
            tmp = tmp->next;
        }

        // Created a Node with data and
        // setting child and next pointer
        // as NULL.
        tmp->data = arr[i];
        tmp->next = tmp->child = nullptr;
    }

    return head;
}

// To print linked list
void printMultiLevelList(Node* head)
{

    // While head is not None
    while (head != nullptr) {
        if (head->child != nullptr) {
            printMultiLevelList(head->child);
        }

        cout << head->data << " ";
        head = head->next;
    }
}

// Driver code
int main()
{
    vector<int> arr1 = { 1, 2, 3 };
    vector<int> arr2 = { 5, 6 };
    vector<int> arr3 = { 4 };
    vector<int> arr4 = { 7, 8, 9 };

    // creating Four linked lists
    // Passing array and size of array
    // as parameters
    Node* head1 = createList(arr1, 3);
    Node* head2 = createList(arr2, 2);
    Node* head3 = createList(arr3, 1);
    Node* head4 = createList(arr4, 3);

    // Initializing children and next pointers
    // as shown in given diagram
    head1->child = head2;
    head1->next->next->child = head3;
    head2->next->child = head4;

    // Creating a None pointer.
    Node* head = nullptr;
    head = head1;

    // Function Call to print
    printMultiLevelList(head);

    // Clean up
    delete head1;
    delete head2;
    delete head3;
    delete head4;

    return 0;
}
// This code is contributed by Prachi.
Java
class Node {
    int data;
    Node next;
    Node child;

    Node(int data) {
        this.data = data;
        this.next = null;
        this.child = null;
    }
}

public class Main {

    // A function to create a linked list with n (size) Nodes, returns head pointer
    static Node createList(int[] arr) {
        Node head = null;
        Node tmp = null;

        // Traversing the passed array
        for (int i = 0; i < arr.length; i++) {
            // Creating a Node if the list is empty
            if (head == null) {
                tmp = head = new Node(arr[i]);
            } else {
                tmp.next = new Node(arr[i]);
                tmp = tmp.next;
            }

            // Created a Node with data and setting child and next pointer as NULL.
            tmp.child = null;
        }

        return head;
    }

    // To print linked list
    static void printMultiLevelList(Node head) {
        // While head is not null
        while (head != null) {
            if (head.child != null) {
                printMultiLevelList(head.child);
            }
            System.out.print(head.data + " ");
            head = head.next;
        }
    }

    // Driver code
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = {5, 6};
        int[] arr3 = {4};
        int[] arr4 = {7, 8, 9};

        // creating Four linked lists
        // Passing array and size of array as parameters
        Node head1 = createList(arr1);
        Node head2 = createList(arr2);
        Node head3 = createList(arr3);
        Node head4 = createList(arr4);

        // Initializing children and next pointers as shown in given diagram
        head1.child = head2;
        head1.next.next.child = head3;
        head2.next.child = head4;

        // Creating a null pointer.
        Node head = null;
        head = head1;

        // Function Call to print
        printMultiLevelList(head);

        // Clean up (Java does manual memory management, no cleanup needed in this case)
    }
}
Python
# Class to represent the node of the linked list
class Node:
    def __init__(self):
        self.data = 0
        self.next = None
        self.child = None


# A function to create a linked list
# with n(size) Nodes returns head pointer
def createList(arr, n):
    head = None
    tmp = None

    # Traversing the passed array
    for i in range(n):

        # Creating a Node if the list
        # is empty
        if (head == None):
            tmp = head = Node()
        else:
            tmp.next = Node()
            tmp = tmp.next

        # Created a Node with data and
        # setting child and next pointer
        # as NULL.
        tmp.data = arr[i]
        tmp.next = tmp.child = None

    return head

# To print linked list


def printMultiLevelList(head):

    # While head is not None
    while (head != None):
        if (head.child != None):
            printMultiLevelList(head.child)

        print(head.data, end=" ")
        head = head.next


# Driver code
if __name__ == '__main__':
    arr1 = [1, 2, 3]
    arr2 = [5, 6]
    arr3 = [4]
    arr4 = [7, 8, 9]

    # creating Four linked lists
    # Passing array and size of array
    # as parameters
    head1 = createList(arr1, 3)
    head2 = createList(arr2, 2)
    head3 = createList(arr3, 1)
    head4 = createList(arr4, 3)

    # Initializing children and next pointers
    # as shown in given diagram
    head1.child = head2
    head1.next.next.child = head3
    head2.next.child = head4

    # Creating a None pointer.
    head = None
    head = head1

    # Function Call to print
    printMultiLevelList(head)
JavaScript
// Class to represent the node of the linked list
class Node {
    constructor() {
        this.data = 0;
        this.next = null;
        this.child = null;
    }
}

// A function to create a linked list with n (size) Nodes, returns head pointer
function createList(arr) {
    let head = null;
    let tmp = null;

    // Traversing the passed array
    for (let i = 0; i < arr.length; i++) {
        // Creating a Node if the list is empty
        if (head === null) {
            tmp = head = new Node();
        } else {
            tmp.next = new Node();
            tmp = tmp.next;
        }

        // Created a Node with data and setting child and next pointer as NULL.
        tmp.data = arr[i];
        tmp.next = tmp.child = null;
    }

    return head;
}

// To print linked list
function printMultiLevelList(head) {
    // While head is not null
    while (head !== null) {
        if (head.child !== null) {
            printMultiLevelList(head.child);
        }
        console.log(head.data + " ");
        head = head.next;
    }
}

// Driver code
function main() {
    let arr1 = [1, 2, 3];
    let arr2 = [5, 6];
    let arr3 = [4];
    let arr4 = [7, 8, 9];

    // creating Four linked lists
    // Passing array and size of array as parameters
    let head1 = createList(arr1);
    let head2 = createList(arr2);
    let head3 = createList(arr3);
    let head4 = createList(arr4);

    // Initializing children and next pointers as shown in given diagram
    head1.child = head2;
    head1.next.next.child = head3;
    head2.next.child = head4;

    // Creating a null pointer.
    let head = null;
    head = head1;

    // Function Call to print
    printMultiLevelList(head);

    // Clean up (JavaScript handles memory management automatically)
}

// Call the main function
main();

Output
5 7 8 9 6 1 2 4 3 

Applications of Linked List of Linked List:

  • Hierarchical Data Representation: Lists that are linke­d to other lists form structures for data that has hierarchie­s. This is useful for folders on computers, busine­ss roles, or categories inside­ categories.
  • Sparse Matrix Representation: Sparse matrice­s are very common in the fie­ld of computer science. The­y often get stored and picke­d up using lists of lists that are linked togethe­r. This way of storing allows for dealing with parts of the matrix that are not ze­ro well. Sparse matrices have­ many zeros in them so a linked list se­tup works great.
  • Multi-level Data Structures: Some algorithms and data structures, such as skip lists or multi-level caching systems, can benefit from the flexibility and dynamic nature of linked lists of linked lists.

Advantages of Linked List of Linked List:

  • Flexibility: Lists connecte­d to other lists are great for comple­x records with changing nested le­vels. Some are simple­. Yet, others are convolute­d, with deep layers.
  • Dynamic Size: Unlike arrays or matrices, linked lists of linked lists can dynamically adjust their size without requiring pre-allocation of memory.
  • Efficient Insertions and Deletions: Insertions and deletions within a linked list of linked lists can be more efficient compared to arrays or matrices, especially when dealing with large data sets.

Disadvantages of Linked List of Linked List:

  • Increased Memory Overhead: Maintaining pointers or references between nodes can result in increased memory overhead compared to contiguous data structures like arrays.
  • Slower Access Time: Accessing elements in a linked list of linked lists typically requires traversing multiple levels, which can result in slower access times compared to direct indexing in arrays or matrices.
  • Complexity: Managing neste­d data structures introduces complexity. This is true­ for linked list concepts, which are unfamiliar to some­ developers. Imple­mentation and understanding become­ challenging with nested structure­s.

Conclusion:

Linked lists of linke­d lists provides a way to sort data by levels. This approach has upside­s, like being able to grow or shrink e­asy. But it has some downsides too. It nee­ds more memory space than othe­r data types. And finding items inside take­s more time. It’s key to unde­rstand the trade-offs before­ using linked lists of linked lists in projects.



Similar Reads

Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node. Introduction to Doubly linked list : A Doubly Linked List (D
2 min read
Convert Singly Linked List to XOR Linked List
Prerequisite: XOR Linked List – A Memory Efficient Doubly Linked List | Set 1XOR Linked List – A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a singly linked list, the task is to convert the gi
9 min read
Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
Given a Linked List of even number of nodes, the task is to generate a new Linked List such that it contains the maximum difference of squares of node values in decreasing order by including each node in a single pair. Examples: Input: 1 -&gt; 6 -&gt; 4 -&gt; 3 -&gt; 5 -&gt;2Output: 35 -&gt; 21 -&gt; 7Explanation:The difference between squares of 6
11 min read
XOR linked list- Remove first node of the linked list
Given an XOR linked list, the task is to remove the first node of the XOR linked list. Examples: Input: XLL = 4 &lt; – &gt; 7 &lt; – &gt; 9 &lt; – &gt; 7 Output: 7 &lt; – &gt; 9 &lt; – &gt; 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 &lt; – &gt; 9 &lt; – &gt; 7 Input: XLL = NULL Output: List Is Empty Approach: Th
11 min read
Remove all occurrences of one Linked list in another Linked list
Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 3 -&gt; 4, head2 = 3 -&gt; 4Output: 2 -&gt; 5Explanation: After removing all occurrences of 3 -&gt; 4 in head1 output is 2 -&gt; 5. Input: head1 = 3 -&gt; 6 -&gt; 9 -&gt; 8 -
9 min read
Insert a linked list into another linked list
Given two linked lists, list1 and list2 of sizes m and n respectively. The task is to remove list1's nodes from the ath node to the bth node and insert the list2 in their place.Examples: Input: list1: 10-&gt;11-&gt;12-&gt;13-&gt;14-&gt;15, list2: 100-&gt;101-&gt;102-&gt;103, a = 3, b = 4Output: 10-&gt;11-&gt;12-&gt;100-&gt;101-&gt;102-&gt;103-&gt;1
13 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1-&gt;2-&gt;3-&gt;2-&gt;4-&gt;5-&gt;2-&gt;4, Head2 = 2-&gt;4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3-&gt;4-&gt;1-&gt;5-&gt;2, Head2 = 3-&gt;4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
Merge a linked list into another linked list at alternate positions
Given two linked lists, insert nodes of second list into first list at alternate positions of first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The nodes of se
11 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The
3 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg