Construct a linked list from 2D matrix

Last Updated : 8 Sep, 2026

Given a Matrix mat of n*n size. Your task is to construct a 2D linked list representation of the given matrix. 

  • Every node of the constructed linked list should have two pointers, right and down.
  • Your function need to return pointer or reference to the linked list node corresponding to mat[0][0].

Examples:

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 *linkMatrix(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 = linkMatrix(mat);
    printList(head);

    return 0;
}
Java
class Node {
    int data;
    Node right, down;

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

class GFG {
    static Node constructUtil(int[][] mat, int i, int j)
    {
        // Base case: if we are out of bounds, return null
        if (i >= mat.length || j >= mat[0].length) {
            return null;
        }

        // 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 array
    static Node linkMatrix(int mat[][])
    {
        // Call the utility function starting from the
        // top-left corner of the matrix
        return constructUtil(mat, 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 mat[][]
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

        Node head = linkMatrix(mat);
        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 linkMatrix(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


# Driver Code
if __name__ == "__main__":

    mat = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]

    head = linkMatrix(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 {
    static Node constructUtil(List<List<int> > mat, int i, int j)
    {
        // Base case: if we are out of bounds, return null
        if (i >= mat.Count || j >= mat[0].Count)
            return null;

        // Create a new Node with the current list 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
    // from a List of Lists
    static Node linkMatrix(List<List<int> > mat)
    {
        // Call the utility function starting
        // from the top-left corner
        return constructUtil(mat, 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> > mat = new List<List<int> >{
            new List<int>{ 1, 2, 3 },
            new List<int>{ 4, 5, 6 },
            new List<int>{ 7, 8, 9 }
        };

        Node head = linkMatrix(mat);

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

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

    // Create a new Node with the current matrix value
    const 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 array
function linkMatrix(mat)
{
    // Call the utility function starting
    // from the top-left corner of the matrix
    return constructUtil(mat, 0, 0);
}

function printList(head)
{
    let currRow = head;

    let res = "";

    while (currRow !== null) {
        let currCol = currRow;

        while (currCol !== null) {
            res += currCol.data + " ";
            currCol = currCol.right;
        }

        res += "\n";
        currRow = currRow.down;
    }

    console.log(res.trim());
}

// Driver Code
const mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ];

const head = linkMatrix(mat);
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++
#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 matrix
// from the given 2D matrix.
Node *linkMatrix(vector<vector<int>> &mat)
{
    int rows = mat.size();
    int cols = mat[0].size();

    // Stores the head node of each row.
    vector<Node *> rowHeads(rows, nullptr);

    // Stores the head of the complete linked matrix.
    Node *mainHead = nullptr;

    // Create a linked list for each row
    // using the right pointers.
    for (int i = 0; i < rows; i++)
    {
        Node *rowTail = nullptr;

        for (int j = 0; j < cols; j++)
        {
            Node *newNode = new Node(mat[i][j]);

            // Set the first node as the main head.
            if (mainHead == nullptr)
            {
                mainHead = newNode;
            }

            // Set the first node of the current row.
            if (rowHeads[i] == nullptr)
            {
                rowHeads[i] = newNode;
            }
            else
            {
                // Link the current node using the right pointer.
                rowTail->right = newNode;
            }

            // Update the tail of the current row.
            rowTail = newNode;
        }
    }

    // Connect corresponding nodes of consecutive rows
    // using the down pointers.
    for (int i = 0; i < rows - 1; i++)
    {
        Node *currentRow = rowHeads[i];
        Node *nextRow = rowHeads[i + 1];

        while (currentRow != nullptr && nextRow != nullptr)
        {
            currentRow->down = nextRow;

            currentRow = currentRow->right;
            nextRow = nextRow->right;
        }
    }

    // Return the top-left node.
    return mainHead;
}

// Function to print the linked matrix.
void printList(Node *head)
{
    Node *currentRow = head;

    while (currentRow != nullptr)
    {
        Node *currentNode = currentRow;

        while (currentNode != nullptr)
        {
            cout << currentNode->data << " ";
            currentNode = currentNode->right;
        }

        cout << endl;
        currentRow = currentRow->down;
    }
}

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

    Node *head = linkMatrix(mat);

    printList(head);

    return 0;
}
Java
class Node {
    int data;
    Node right, down;

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

class GFG {
    // Function to construct the linked matrix
    // from the given 2D matrix.
    static Node linkMatrix(int[][] mat)
    {
        int rows = mat.length;
        int cols = mat[0].length;

        // Stores the head node of each row.
        Node[] rowHeads = new Node[rows];

        // Stores the head of the complete linked matrix.
        Node mainHead = null;

        // Create a linked list for each row
        // using the right pointers.
        for (int i = 0; i < rows; i++) {
            Node rowTail = null;

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

                // Set the first node as the main head.
                if (mainHead == null) {
                    mainHead = newNode;
                }

                // Set the first node of the current row.
                if (rowHeads[i] == null) {
                    rowHeads[i] = newNode;
                }
                else {
                    // Link the current node using the right
                    // pointer.
                    rowTail.right = newNode;
                }

                // Update the tail of the current row.
                rowTail = newNode;
            }
        }

        // Connect corresponding nodes of consecutive rows
        // using the down pointers.
        for (int i = 0; i < rows - 1; i++) {
            Node currentRow = rowHeads[i];
            Node nextRow = rowHeads[i + 1];

            while (currentRow != null && nextRow != null) {
                currentRow.down = nextRow;

                currentRow = currentRow.right;
                nextRow = nextRow.right;
            }
        }

        // Return the top-left node.
        return mainHead;
    }

    // Function to print the linked matrix.
    static void printList(Node head)
    {
        Node currentRow = head;

        while (currentRow != null) {
            Node currentNode = currentRow;

            while (currentNode != null) {
                System.out.print(currentNode.data + " ");
                currentNode = currentNode.right;
            }

            System.out.println();
            currentRow = currentRow.down;
        }
    }

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

        Node head = linkMatrix(mat);

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


# Function to construct the linked matrix
# from the given 2D matrix.
def linkMatrix(mat):
    rows = len(mat)
    cols = len(mat[0])

    # Stores the head node of each row.
    rowHeads = [None] * rows

    # Stores the head of the complete linked matrix.
    mainHead = None

    # Create a linked list for each row
    # using the right pointers.
    for i in range(rows):
        rowTail = None

        for j in range(cols):
            newNode = Node(mat[i][j])

            # Set the first node as the main head.
            if mainHead is None:
                mainHead = newNode

            # Set the first node of the current row.
            if rowHeads[i] is None:
                rowHeads[i] = newNode
            else:
                # Link the current node using the right pointer.
                rowTail.right = newNode

            # Update the tail of the current row.
            rowTail = newNode

    # Connect corresponding nodes of consecutive rows
    # using the down pointers.
    for i in range(rows - 1):
        currentRow = rowHeads[i]
        nextRow = rowHeads[i + 1]

        while currentRow is not None and nextRow is not None:
            currentRow.down = nextRow

            currentRow = currentRow.right
            nextRow = nextRow.right

    # Return the top-left node.
    return mainHead


# Function to print the linked matrix.
def printList(head):
    currentRow = head

    while currentRow is not None:
        currentNode = currentRow

        while currentNode is not None:
            print(currentNode.data, end=" ")
            currentNode = currentNode.right

        print()
        currentRow = currentRow.down


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

    head = linkMatrix(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 {

    // Function to construct the linked matrix
    // from the given 2D matrix.
    static Node linkMatrix(List<List<int> > mat)
    {
        int rows = mat.Count;
        int cols = mat[0].Count;

        // Stores the head node of each row.
        List<Node> rowHeads
            = new List<Node>(new Node[rows]);

        // Stores the head of the complete linked matrix.
        Node mainHead = null;

        // Create a linked list for each row
        // using the right pointers.
        for (int i = 0; i < rows; i++) {
            Node rowTail = null;

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

                // Set the first node as the main head.
                if (mainHead == null) {
                    mainHead = newNode;
                }

                // Set the first node of the current row.
                if (rowHeads[i] == null) {
                    rowHeads[i] = newNode;
                }
                else {
                    // Link the current node using the right
                    // pointer.
                    rowTail.right = newNode;
                }

                // Update the tail of the current row.
                rowTail = newNode;
            }
        }

        // Connect corresponding nodes of consecutive rows
        // using the down pointers.
        for (int i = 0; i < rows - 1; i++) {
            Node currentRow = rowHeads[i];
            Node nextRow = rowHeads[i + 1];

            while (currentRow != null && nextRow != null) {
                currentRow.down = nextRow;

                currentRow = currentRow.right;
                nextRow = nextRow.right;
            }
        }

        // Return the top-left node.
        return mainHead;
    }

    // Function to print the linked matrix.
    static void printList(Node head)
    {
        Node currentRow = head;

        while (currentRow != null) {
            Node currentNode = currentRow;

            while (currentNode != null) {
                Console.Write(currentNode.data + " ");
                currentNode = currentNode.right;
            }

            Console.WriteLine();
            currentRow = currentRow.down;
        }
    }

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

        Node head = linkMatrix(mat);

        printList(head);
    }
}
JavaScript
class Node {
    constructor(x)
    {
        this.data = x;
        this.right = null;
        this.down = null;
    }
}

// Function to construct the linked matrix
// from the given 2D matrix.
function linkMatrix(mat)
{
    const rows = mat.length;
    const cols = mat[0].length;

    // Stores the head node of each row.
    const rowHeads = new Array(rows).fill(null);

    // Stores the head of the complete linked matrix.
    let mainHead = null;

    // Create a linked list for each row
    // using the right pointers.
    for (let i = 0; i < rows; i++) {
        let rowTail = null;

        for (let j = 0; j < cols; j++) {
            const newNode = new Node(mat[i][j]);

            // Set the first node as the main head.
            if (mainHead === null) {
                mainHead = newNode;
            }

            // Set the first node of the current row.
            if (rowHeads[i] === null) {
                rowHeads[i] = newNode;
            }
            else {
                // Link the current node using the right
                // pointer.
                rowTail.right = newNode;
            }

            // Update the tail of the current row.
            rowTail = newNode;
        }
    }

    // Connect corresponding nodes of consecutive rows
    // using the down pointers.
    for (let i = 0; i < rows - 1; i++) {
        let currentRow = rowHeads[i];
        let nextRow = rowHeads[i + 1];

        while (currentRow !== null && nextRow !== null) {
            currentRow.down = nextRow;

            currentRow = currentRow.right;
            nextRow = nextRow.right;
        }
    }

    // Return the top-left node.
    return mainHead;
}

// Function to print the linked matrix.
function printList(head)
{
    let currentRow = head;

    while (currentRow !== null) {
        let currentNode = currentRow;

        while (currentNode !== null) {
            process.stdout.write(currentNode.data + " ");
            currentNode = currentNode.right;
        }

        console.log();
        currentRow = currentRow.down;
    }
}

// Driver Code
const mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ];

const head = linkMatrix(mat);

printList(head);

Output
1 2 3 
4 5 6 
7 8 9 
Comment