Construct a linked list from 2D matrix

Last Updated : 3 May, 2026

Given a matrix mat of size n × n, construct a 2D linked list that represents the matrix, where each node stores the value of a cell and contains pointers to its right and down neighbors.

Example:

Input : mat = [[1 2 3]
[4 5 6]
[7 8 9]]
Output :

Construct-a-linked-list-from-2D-matrix-1

Input : mat = [[23 28]
[23 28]]
Output :

Construct-a-linked-list-from-2D-matrix-2
Try It Yourself
redirect icon

Recursive Approach - O(n^2) Time and O(n^2) Space

Start at the (0, 0) position of the given matrix and create a node for each matrix element. Each node’s right pointer links to the next element in the same row, while its down pointer connects to the element directly below in the column

Follow the steps below to solve the problem:

  • Recursively do the following steps for any cell in the matrix:
  • If the cell is out of bounds, return null.
  • Create a new Node with the value from the matrix for the current cell.
  • Recursively construct the right node for the next cell in the row.
  • Recursively construct the down node for the next cell in the column.
  • Finally return the root Node.
C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *right, *down;

    Node(int x) {
        data = x;
        right = down = nullptr;
    }
};

// Function to recursively construct the linked matrix 
// from a given 2D vector
Node* constructUtil(vector<vector<int>>& mat, 
                                      int i, int j) {
  
    // Base case: if we are out of bounds, return NULL
    if (i >= mat.size() || j >= mat[0].size()) {
        return nullptr;
    }

    // Create a new Node with the current matrix value
    Node* curr = new Node(mat[i][j]);

    // Recursively construct the right and down pointers
    curr->right = constructUtil(mat, i, j + 1);
    curr->down = constructUtil(mat, i + 1, j);

    // Return the constructed Node
    return curr;
}

// Function to construct the linked matrix given a 2D vector
Node* constructLinkedMatrix(vector<vector<int>>& mat) {
  
    // Call the utility function starting 
    // from the top-left corner of the matrix
    return constructUtil(mat, 0, 0);
}

void printList(Node *head) {
    Node *currRow = head;
    while (currRow != nullptr) {
        Node *currCol = currRow;
        while (currCol != nullptr) {
            cout << currCol->data << " ";
            currCol = currCol->right;
        }
        cout << endl;
        currRow = currRow->down;
    }
}

int main() {
  

    vector<vector<int>> mat = { { 1, 2, 3 },
                                { 4, 5, 6 },
                                { 7, 8, 9 } };

    Node* head = constructLinkedMatrix(mat);
    printList(head);

    return 0;
}
Java
import java.util.ArrayList;

class Node {
    int data;
    Node right, down;

    Node(int data) {
        this.data = data;
        this.right = null;
        this.down = null;
    }
}

class GfG {

    // Function to recursively construct the linked
    // matrix from a given 2D array
    static Node constructUtil(int[][] arr, int i, int j) {
      
        // Base case: if we are out of bounds, return null
        if (i >= arr.length || j >= arr[0].length) {
            return null;
        }

        // Create a new Node with the current
        // matrix value
        Node curr = new Node(arr[i][j]);

        // Recursively construct the right
        // and down pointers
        curr.right = constructUtil(arr, i, j + 1);
        curr.down = constructUtil(arr, i + 1, j);

        // Return the constructed Node
        return curr;
    }

    // Function to construct the linked 
    // matrix given a 2D array
    static Node construct(int arr[][]) {
      
        // Call the utility function starting from the 
        // top-left corner of the matrix
        return constructUtil(arr, 0, 0);
    }

    static void printList(Node head) {
        Node currRow = head;
        while (currRow != null) {
            Node currCol = currRow;
            while (currCol != null) {
                System.out.print(currCol.data + " ");
                currCol = currCol.right;
            }
            System.out.println();
            currRow = currRow.down;
        }
    }

    public static void main(String[] args) {
      
        int arr[][] = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        Node head = construct(arr);
        printList(head);
    }
}
Python
 class Node:
    def __init__(self, data):
        self.data = data
        self.right = None
        self.down = None

def constructUtil(mat, i, j):
  
    # Base case: if we are out of bounds, return None
    if i >= len(mat) or j >= len(mat[0]):
        return None

    # Create a new Node with the current matrix value
    curr = Node(mat[i][j])

    # Recursively construct the right and down pointers
    curr.right = constructUtil(mat, i, j + 1)
    curr.down = constructUtil(mat, i + 1, j)

    # Return the constructed Node
    return curr

def constructLinkedMatrix(mat):
  
    # Call the utility function starting 
    # from the top-left corner of the matrix
    return constructUtil(mat, 0, 0)

def printList(head):
    currRow = head
    while currRow:
        currCol = currRow
        while currCol:
            print(currCol.data, end=" ")
            currCol = currCol.right
        print()
        currRow = currRow.down

if __name__ == "__main__":
  
    mat = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    head = constructLinkedMatrix(mat)
    printList(head)
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node right, down;

    public Node(int x) {
        data = x;
        right = down = null;
    }
}

class GfG {
    
    // Recursive utility function to construct 
    // the linked matrix from a 2D List
    static Node ConstructUtil(List<List<int>> arr, 
                                        int i, int j) {
      
        // Base case: if we are out of bounds, return null
        if (i >= arr.Count || j >= arr[0].Count)
            return null;

        // Create a new Node with the current list value
        Node curr = new Node(arr[i][j]);

        // Recursively construct the right and 
        // down pointers
        curr.right = ConstructUtil(arr, i, j + 1);
        curr.down = ConstructUtil(arr, i + 1, j);

        // Return the constructed Node
        return curr;
    }

    // Function to construct the linked matrix 
    // from a List of Lists
    static Node Construct(List<List<int>> arr) {
      
        // Call the utility function starting 
        // from the top-left corner
        return ConstructUtil(arr, 0, 0);
    }

    static void PrintList(Node head) {
        Node currRow = head;
        while (currRow != null) {
            Node currCol = currRow;
            while (currCol != null) {
                Console.Write(currCol.data + " ");
                currCol = currCol.right;
            }
            Console.WriteLine();
            currRow = currRow.down;
        }
    }

    static void Main(string[] args) {
      
        List<List<int>> arr = new List<List<int>> {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 },
            new List<int> { 7, 8, 9 }
        };

        Node head = Construct(arr);
        PrintList(head);
    }
}
JavaScript
 class Node {
    constructor(data) {
        this.data = data;
        this.right = null;
        this.down = null;
    }
}

// Recursive utility function to construct 
// the linked matrix
function constructUtil(arr, i, j) {

    // Base case: if out of bounds, return null
    if (i >= arr.length || j >= arr[0].length) {
        return null;
    }

    // Create a new Node with the current array value
    const curr = new Node(arr[i][j]);

    // Recursively construct the right and down pointers
    curr.right = constructUtil(arr, i, j + 1);
    curr.down = constructUtil(arr, i + 1, j);

    // Return the constructed Node
    return curr;
}

// Function to construct the linked matrix from a 2D array
function constructLinkedMatrix(arr) {

    // Start from the top-left corner
    return constructUtil(arr, 0, 0);
}

function printList(head) {
    let currRow = head;
    while (currRow !== null) {
        let currCol = currRow;
        while (currCol !== null) {
            console.log(currCol.data + " ");
            currCol = currCol.right;
        }
        console.log();
        currRow = currRow.down;
    }
}

const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

const head = constructLinkedMatrix(arr);
printList(head);

Output
1 2 3 
4 5 6 
7 8 9 

Iterative Approach - O(n^2) Time and O(n^2) Space

The approach involves creating m linked lists. Each node in these linked lists stores a reference to its right neighbor. The head pointers of each linked list are maintained in an array. After constructing the linked lists, we traverse through them and for each i-th and (i+1)-th list, we establish the down pointers of each node in i-th list to point to the corresponding node in (i+1)-th list.

  • The idea is to create m linked lists (m = number of rows) whose each node stores its right node. The head pointers of each m linked lists are stored in an array of nodes.
  • Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each node of ith list to its corresponding node of (i+1)th list. 
Construct-a-linked-list-from-2D-matrix-3
C++
// C++ to implement linked matrix 
// from a 2D matrix iteratively 
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *right, *down;

    Node(int x) {
        data = x;
        right = down = nullptr;
    }
};

// Function to construct the linked list from the given
/// matrix and return the head pointer
Node* constructLinkedMatrix(vector<vector<int>>& mat) {
    int m = mat.size();
    int n = mat[0].size();

    // Stores the head of the linked list
    Node* mainhead = nullptr;

    // Stores the head of linked lists of each row
    vector<Node*> head(m);
    Node *rightcurr, *newptr;

    // Create m linked lists by setting all 
    // the right nodes of every row
    for (int i = 0; i < m; i++) {
        head[i] = nullptr;

        for (int j = 0; j < n; j++) {
            newptr = new Node(mat[i][j]);

            // Assign the first node as the mainhead
            if (!mainhead) {
                mainhead = newptr;
            }

            // Set the head for the row or link 
            // the current node
            if (!head[i]) {
                head[i] = newptr;
            } 
            else {
                rightcurr->right = newptr;
            }

            rightcurr = newptr;
        }
    }

    // Set the down pointers for nodes in consecutive rows
    for (int i = 0; i < m - 1; i++) {
        Node *curr1 = head[i], *curr2 = head[i + 1];

        // Link corresponding nodes in consecutive rows
        while (curr1 && curr2) {
            curr1->down = curr2;
            curr1 = curr1->right;
            curr2 = curr2->right;
        }
    }

    // Return the mainhead of the constructed 
    // linked list
    return mainhead;
}

void printList(Node *head) {
  
    Node *currRow = head;
    while (currRow != nullptr) {
        Node *currCol = currRow;
        while (currCol != nullptr) {
            cout << currCol->data << " ";
            currCol = currCol->right;
        }
        cout << endl;
        currRow = currRow->down;
    }
}

int main() {
    
    vector<vector<int>> mat = { { 1, 2, 3 },
                                { 4, 5, 6 },
                                { 7, 8, 9 } };

    Node* head = constructLinkedMatrix(mat);
    printList(head);

    return 0;
}
Java
// Java to implement linked matrix 
// from a 2D matrix iteratively 
import java.util.ArrayList;

class Node {
    int data;
    Node right, down;

    Node(int data) {
        this.data = data;
        this.right = null;
        this.down = null;
    }
}

class GfG {

    // Function to construct the linked 
    // matrix from a 2D array
    static Node construct(int arr[][]) {
        int m = arr.length;     
        int n = arr[0].length; 

        // Stores the head of the linked list
        Node mainhead = null;

        // ArrayList to store the heads of 
        // linked lists for each row
        ArrayList<Node> head = new ArrayList<>(m);

        Node rightcurr = null;

        // Create m linked lists by setting all
        // the right nodes of every row
        for (int i = 0; i < m; i++) {
            head.add(null);
            for (int j = 0; j < n; j++) {
              
                Node newptr = new Node(arr[i][j]);

                // Assign the first node as the mainhead
                if (mainhead == null) {
                    mainhead = newptr;
                }

                // Set the head for the row or link 
                // the current node
                if (head.get(i) == null) {
                    head.set(i, newptr);
                } else {
                    rightcurr.right = newptr;
                }

                rightcurr = newptr;
            }
        }

        // Set the down pointers for nodes in 
        // consecutive rows
        for (int i = 0; i < m - 1; i++) {
            Node curr1 = head.get(i);
            Node curr2 = head.get(i + 1);

            // Link corresponding nodes in consecutive rows
            while (curr1 != null && curr2 != null) {
                curr1.down = curr2;
                curr1 = curr1.right;
                curr2 = curr2.right;
            }
        }

        // Return the mainhead of the constructed 
        // linked list
        return mainhead;
    }

    static void printList(Node head) {
        Node currRow = head;
        while (currRow != null) {
            Node currCol = currRow;
            while (currCol != null) {
                System.out.print(currCol.data + " ");
                currCol = currCol.right;
            }
            System.out.println();
            currRow = currRow.down;
        }
    }

    public static void main(String[] args) {

        int arr[][] = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        Node head = construct(arr);
        printList(head);
    }
}
Python
# Python to implement linked matrix 
# from a 2D matrix iteratively 
class Node:
    def __init__(self, data):
  
        self.data = data
        self.right = None
        self.down = None
    
def constructLinkedMatrix(mat):
    m = len(mat)
    n = len(mat[0])

    # Stores the head of the linked list
    mainhead = None

    # Stores the head of linked lists of each row
    head = [None] * m
    rightcurr = None

    # Create m linked lists by setting all the 
    # right nodes of every row
    for i in range(m):
        head[i] = None
        for j in range(n):
            newptr = Node(mat[i][j])

            # Assign the first node as the mainhead
            if not mainhead:
                mainhead = newptr

            # Set the head for the row or link the 
            # current node
            if not head[i]:
                head[i] = newptr
            else:
                rightcurr.right = newptr

            rightcurr = newptr

    # Set the down pointers for nodes in consecutive rows
    for i in range(m - 1):
        curr1 = head[i]
        curr2 = head[i + 1]

        # Link corresponding nodes in consecutive rows
        while curr1 and curr2:
            curr1.down = curr2
            curr1 = curr1.right
            curr2 = curr2.right

    # Return the mainhead of the constructed linked list
    return mainhead

def printList(head):
    currRow = head
    while currRow:
        currCol = currRow
        while currCol:
            print(currCol.data, end=" ")
            currCol = currCol.right
        print()
        currRow = currRow.down

if __name__ == "__main__":
  
    mat = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    head = constructLinkedMatrix(mat)

    printList(head)
C#
// C# to implement linked matrix 
// from a 2D matrix iteratively 
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node right, down;

    public Node(int x) {
        data = x;
        right = down = null;
    }
}

class GfG {

    // Function to construct the linked matrix 
    // from a List of Lists
    static Node Construct(List<List<int>> arr) {
        int m = arr.Count;  
        int n = arr[0].Count;  

        // Stores the head of the linked list
        Node mainhead = null;

        // List to store the heads of linked 
        // lists for each row
        List<Node> head = new List<Node>(m);

        Node rightcurr = null;

        // Create m linked lists by setting all the 
        // right nodes of every row
        for (int i = 0; i < m; i++) {
            head.Add(null);
            for (int j = 0; j < n; j++) {
                Node newptr = new Node(arr[i][j]);

                // Assign the first node as the mainhead
                if (mainhead == null) {
                    mainhead = newptr;
                }

                // Set the head for the row or link 
                // the current node
                if (head[i] == null) {
                    head[i] = newptr;
                } 
                else {
                    rightcurr.right = newptr;
                }

                rightcurr = newptr;
            }
        }

        // Set the down pointers for nodes 
        // in consecutive rows
        for (int i = 0; i < m - 1; i++) {
            Node curr1 = head[i];
            Node curr2 = head[i + 1];

            // Link corresponding nodes in 
            // consecutive rows
            while (curr1 != null && curr2 != null) {
                curr1.down = curr2;
                curr1 = curr1.right;
                curr2 = curr2.right;
            }
        }

        // Return the mainhead of the 
        // constructed linked list
        return mainhead;
    }

    static void PrintList(Node head) {
        Node currRow = head;
        while (currRow != null) {
            Node currCol = currRow;
            while (currCol != null) {
                Console.Write(currCol.data + " ");
                currCol = currCol.right;
            }
            Console.WriteLine();
            currRow = currRow.down;
        }
    }

    static void Main(string[] args) {
      
        List<List<int>> arr = new List<List<int>> {
            new List<int> { 1, 2, 3 },
            new List<int> { 4, 5, 6 },
            new List<int> { 7, 8, 9 }
        };

        Node head = Construct(arr);
        PrintList(head);
    }
}
JavaScript
// Javascript to implement linked matrix 
// from a 2D matrix iteratively 
class Node {
    constructor(data) {
        this.data = data;
        this.right = null;
        this.down = null;
    }
}

// Function to construct the linked matrix 
// from a 2D array
function constructLinkedMatrix(arr) {
    const m = arr.length;      
    const n = arr[0].length;  

    // Stores the head of the linked list
    let mainHead = null;

    // Array to store the heads of linked 
    // lists for each row
    const head = new Array(m).fill(null);
    let rightCurr = null;

    // Create m linked lists by setting all the 
    // right nodes of every row
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            const newPtr = new Node(arr[i][j]);

            // Assign the first node as the mainHead
            if (mainHead === null) {
                mainHead = newPtr;
            }

            // Set the head for the row or 
            // link the current node
            if (head[i] === null) {
                head[i] = newPtr;
            } 
            else {
                rightCurr.right = newPtr;
            }

            rightCurr = newPtr;
        }
    }

    // Set the down pointers for nodes in 
    // consecutive rows
    for (let i = 0; i < m - 1; i++) {
        let curr1 = head[i];
        let curr2 = head[i + 1];

        // Link corresponding nodes in consecutive rows
        while (curr1 && curr2) {
            curr1.down = curr2;
            curr1 = curr1.right;
            curr2 = curr2.right;
        }
    }

    // Return the mainHead of the constructed 
    // linked list
    return mainHead;
}

function printList(head) {
    let currRow = head;
    while (currRow !== null) {
        let currCol = currRow;
        while (currCol !== null) {
            console.log(currCol.data + " ");
            currCol = currCol.right;
        }
        console.log();
        currRow = currRow.down;
    }
}

const arr = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

const head = constructLinkedMatrix(arr);
printList(head);

Output
1 2 3 
4 5 6 
7 8 9 


Comment