The Wayback Machine - https://web.archive.org/web/20241006121644/https://www.geeksforgeeks.org/construct-linked-list-2d-matrix/
Open In App

Construct a linked list from 2D matrix

Last Updated : 26 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
67.62%
13.4K

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

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

[Expected Approach – 1] Recursive Approach – O(n^2) Time and O(n^2) Space

To recursively construct a linked matrix from a 2D matrix, 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. If the current position is out of bounds, return NULL to end recursive call. This process continues recursively, creating and linking nodes until the entire matrix is transformed into a linked matrix with appropriate horizontal and vertical connections.

Follow the steps below to solve the problem:

  • First, create a variable of Node type, which will store the value and the addresses of its right and bottom nodes corresponding to a cell in the matrix.
  • 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.

Below is the implementation of the above approach:

C++
// C++ to implement linked matrix 
// from a 2D matrix recursively 
#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
// Java to implement linked matrix 
// from a 2D matrix recursively 
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
# Python to implement linked matrix 
# from a 2D matrix recursively 
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#
// C# to implement linked matrix 
// from a 2D matrix recursively 
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
// Javascript to implement linked matrix 
// from a 2D matrix recursively 
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 

Time complexity: O(n^2), since each element in the 2D matrix is visited once to create the corresponding node in the linked structure.
Auxiliary space: O(n^2), due to the storage needed for each node in the linked matrix.

[Expected Approach – 2] Iterative Approach – O(n^2) Time and O(n^2) Space

The approach involves creating m linked lists, where m represents the number of rows in a given 2D matrix. 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. Please refer to Construct a linked list from 2D matrix (Iterative Approach) for implementation.



Similar Reads

Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Construct a linked list from 2D matrix (Iterative Approach)
Given a Matrix mat of n*n size, the task is to construct a 2D linked list representation of the given matrix. Example: Input : mat = [[1 2 3] [4 5 6] [7 8 9]]Output : Input : mat = [[23 28] [23 28]]Output : Approach: To Construct a linked list from 2D matrix iteratively follow the steps below: The idea is to create m linked lists (m = number of row
9 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
Given a matrix arr[][] of dimensions N * M, the task is to generate a matrix such that any cell (r, c) stores the sum of adjacent elements present horizontally, vertically, and diagonally in the given matrix. Examples: Input: arr[][] = {{1, 3}, {2, 4}}Output: {{9, 7}, {8, 6}}Explanation: Matrix is constructed by the following operations: For cell (
9 min read
Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
Given two values m and n, fill a matrix of size 'm*n' in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n. Examples: Input : m = 4, n = 4 Output : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input : m = 3, n = 4 Output : 1 2 3 4 10 11 12 5 9 8 7 6 The idea is based on Print a given matrix in spiral form. We create a matrix o
10 min read
Construct Complete Binary Tree from its Linked List Representation
Given the Linked List Representation of a Complete Binary Tree, the task is to construct the complete binary tree. The complete binary tree is represented as a linked list in a way where if the root node is stored at position i, its left, and right children are stored at position 2*i+1, and 2*i+2 respectively. Examples: Input: 1->2->3>4-
10 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
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 < – > 7 < – > 9 < – > 7 Output: 7 < – > 9 < – > 7 Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 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 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -> 5. Input: head1 = 3 -> 6 -> 9 -> 8 -
9 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->2->3->2->4->5->2->4, Head2 = 2->4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3->4->1->5->2, Head2 = 3->4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 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
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< – > 6 < – > 8 < – > 11 < – > 3, K = 3 Output: 8 < – > 6 < – > 7 < – > 3 < – > 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 < – > 6
13 min read
XOR Linked List: Remove last node of the Linked List
Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<–>7<–>9<–>7Output: 4<–>7<–>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<–>7<–>9 Input: 10Output: List is emptyExplanation: After deleting the only node present
15+ min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List - Pairwise swap elements of a given linked list
Given a XOR linked list, the task is to pairwise swap the elements of the given XOR linked list . Examples: Input: 4 <-> 7 <-> 9 <-> 7Output: 7 <-> 4 <-> 7 <-> 9Explanation:First pair of nodes are swapped to formed the sequence {4, 7} and second pair of nodes are swapped to form the sequence {9, 7}. Input: 1 <
12 min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1, K = 3Output: 7<–>6<–>8<–>1<–>3<–>11 Input: LL: 7 <–> 6 <–> 8 <–> 11 <–> 3 <–> 1 <–
14 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Linked List of Linked List
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 L
9 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
Create new linked list from two given linked list with greater element at each node
Given two linked list of the same size, the task is to create a new linked list using those linked lists. The condition is that the greater node among both linked list will be added to the new linked list.Examples: Input: list1 = 5->2->3->8list2 = 1->7->4->5Output: New list = 5->7->4->8Input: list1 = 2->8->9->3li
8 min read
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 (
2 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2->4->6->7->5 Output: trueExplanation: As shown in figure the first a
12 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->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Insert a linked list into another linked list
Given two linked lists, head1 and head2 of sizes m and n respectively. The task is to remove head1's nodes from the ath node to the bth node and insert head2 in their place. Examples: Input: a = 3, b = 4head1: 10 -> 11 -> 12 -> 13 -> 14 -> 15, head2: 100 -> 101 -> 102 -> 103Output: 10 -> 11 -> 12 -> 100 -> 101 -
10 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -> 4 -> 6 -> 8 -> 10 -> 12 -> NULLOutput: Explanation: Singly l
11 min read
Merge a linked list into another linked list at alternate positions
Given two singly linked lists, The task is to insert nodes of the second list into the first list at alternate positions of the first list and leave the remaining nodes of the second list if it is longer. Example: Input: head1: 1->2->3 , head2: 4->5->6->7->8Output: head1: 1->4->2->5->3->6 , head2: 7->8 Input: hea
8 min read
Construct Binary Tree from Ancestor Matrix | Top Down Approach
Given an ancestor matrix mat[n][n] where the ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of j mat[i][j] = 0, otherwise Construct a Binary Tree from the given ancestor matrix where all its values of nodes are from 0 to n-1. It may be assumed that the input provided by the program is valid and the tree can be constructed out o
10 min read
Construct a matrix such that union of ith row and ith column contains every element from 1 to 2N-1
Given a number N, the task is to construct a square matrix of N * N where the union of elements in some ith row with the ith column contains every element in the range [1, 2*N-1]. If no such matrix exists, print -1.Note: There can be multiple possible solutions for a particular N Examples: Input: N = 6 Output: 6 4 2 5 3 1 10 6 5 3 1 2 8 11 6 1 4 3
11 min read
Article Tags :
Practice Tags :