Construct a linked list from 2D matrix - GeeksforGeeks

07 Jun, 2021
Given a matrix. Convert it into a linked list matrix such that each node is connected to its next right and down node.Example:  
Input : 2D matrix 
1 2 3
4 5 6
7 8 9

Output :
1 -> 2 -> 3 -> NULL
|    |    |
v    v    v
4 -> 5 -> 6 -> NULL
|    |    |
v    v    v
7 -> 8 -> 9 -> NULL
|    |    |
v    v    v
NULL NULL NULL
Question Source: Factset Interview Experience | Set 9 
The idea is to construct a new node for every element of matrix and recursively create its down and right nodes.  
C++
Java
Python3
C#
Javascript
// CPP program to construct a linked list// from given 2D matrix#include <bits/stdc++.h>using namespace std; // struct node of linked liststruct Node {    int data;    Node* right, *down;}; // returns head pointer of linked list// constructed from 2D matrixNode* construct(int arr[][3], int i, int j,                              int m, int n){    // return if i or j is out of bounds    if (i > n - 1 || j > m - 1)        return NULL;     // create a new node for current i and j    // and recursively allocate its down and    // right pointers    Node* temp = new Node();    temp->data = arr[i][j];    temp->right = construct(arr, i, j + 1, m, n);    temp->down  = construct(arr, i + 1, j, m, n);    return temp;} // utility function for displaying// linked list datavoid display(Node* head){    // pointer to move right    Node* Rp;     // pointer to move down    Node* Dp = head;     // loop till node->down is not NULL    while (Dp) {        Rp = Dp;         // loop till node->right is not NULL        while (Rp) {            cout << Rp->data << " ";            Rp = Rp->right;        }        cout << "\n";        Dp = Dp->down;    }} // driver programint main(){    // 2D matrix    int arr[][3] = {        { 1, 2, 3 },        { 4, 5, 6 },        { 7, 8, 9 }    };     int m = 3, n = 3;    Node* head = construct(arr, 0, 0, m, n);    display(head);    return 0;}
// Java program to construct a linked list// from given 2D matrixpublic class Linked_list_2D_Matrix {     // node of linked list    static class Node {        int data;        Node right;        Node down;    };     // returns head pointer of linked list    // constructed from 2D matrix    static Node construct(int arr[][], int i, int j,                                     int m, int n) {                 // return if i or j is out of bounds        if (i > n - 1 || j > m - 1)            return null;         // create a new node for current i and j        // and recursively allocate its down and        // right pointers        Node temp = new Node();        temp.data = arr[i][j];        temp.right = construct(arr, i, j + 1, m, n);        temp.down = construct(arr, i + 1, j, m, n);        return temp;    }     // utility function for displaying    // linked list data    static void display(Node head) {                 // pointer to move right        Node Rp;         // pointer to move down        Node Dp = head;         // loop till node->down is not NULL        while (Dp != null) {            Rp = Dp;             // loop till node->right is not NULL            while (Rp != null) {                System.out.print(Rp.data + " ");                Rp = Rp.right;            }            System.out.println();            Dp = Dp.down;        }    }     // driver program    public static void main(String args[]) {        // 2D matrix        int arr[][] = { { 1, 2, 3 },                        { 4, 5, 6 },                       { 7, 8, 9 } };         int m = 3, n = 3;        Node head = construct(arr, 0, 0, m, n);        display(head);    } }// This code is contributed by Sumit Ghosh
    # Python3 program to construct a linked list# from given 2D matriximport math # struct node of linked listclass Node:    def __init__(self, data):        self.data = data        self.right = None        self.down = None # returns head pointer of linked list# constructed from 2D matrixdef construct(arr, i, j, m, n):         # return if i or j is out of bounds    if (i > n - 1 or j > m - 1):        return None     # create a new node for current i and j    # and recursively allocate its down and    # right pointers    temp = Node(arr[i][j])    temp.data = arr[i][j]    temp.right = construct(arr, i, j + 1, m, n)    temp.down = construct(arr, i + 1, j, m, n)    return temp # utility function for displaying# linked list datadef display(head):         # pointer to move right    # Rp     # pointer to move down    Dp = head     # loop till node.down is not None    while (Dp):        Rp = Dp         # loop till node.right is not None        while (Rp):            print(Rp.data, end = " ")            Rp = Rp.right                 print()        Dp = Dp.down     # Driver Codeif __name__=='__main__':    # 2D matrix    arr = [[ 1, 2, 3 ],           [ 4, 5, 6 ],           [ 7, 8, 9 ]]     m, n = 3, 3    head = construct(arr, 0, 0, m, n)    display(head)     # This code is contributed by AbhiThakur
// C# program to construct a linked list// from given 2D matrixusing System;     public class Linked_list_2D_Matrix{     // node of linked list    public class Node    {        public int data;        public Node right;        public Node down;    };     // returns head pointer of linked list    // constructed from 2D matrix    static Node construct(int [,]arr, int i, int j,                                    int m, int n)    {                 // return if i or j is out of bounds        if (i > n - 1 || j > m - 1)            return null;         // create a new node for current i and j        // and recursively allocate its down and        // right pointers        Node temp = new Node();        temp.data = arr[i, j];        temp.right = construct(arr, i, j + 1, m, n);        temp.down = construct(arr, i + 1, j, m, n);        return temp;    }     // utility function for displaying    // linked list data    static void display(Node head)    {                 // pointer to move right        Node Rp;         // pointer to move down        Node Dp = head;         // loop till node->down is not NULL        while (Dp != null)        {            Rp = Dp;             // loop till node->right is not NULL            while (Rp != null)            {                Console.Write(Rp.data + " ");                Rp = Rp.right;            }            Console.WriteLine();            Dp = Dp.down;        }    }     // Driver program    public static void Main()    {        // 2D matrix        int [,]arr = { { 1, 2, 3 },                        { 4, 5, 6 },                    { 7, 8, 9 } };         int m = 3, n = 3;        Node head = construct(arr, 0, 0, m, n);        display(head);    }} /* This code contributed by PrinciRaj1992 */
<script> // JavaScript program to construct a linked list// from given 2D matrix     // node of linked list     class Node {            constructor(val) {                this.data = val;                this.down = null;                this.right = null;            }        }     // returns head pointer of linked list    // constructed from 2D matrix    function construct(arr , i , j , m , n) {         // return if i or j is out of bounds        if (i > n - 1 || j > m - 1)            return null;         // create a new node for current i and j        // and recursively allocate its down and        // right pointers        var temp = new Node();        temp.data = arr[i][j];        temp.right = construct(arr, i, j + 1, m, n);        temp.down = construct(arr, i + 1, j, m, n);        return temp;    }     // utility function for displaying    // linked list data    function display(head) {         // pointer to move right        var Rp;         // pointer to move down        var Dp = head;         // loop till node->down is not NULL        while (Dp != null) {            Rp = Dp;             // loop till node->right is not NULL            while (Rp != null) {                document.write(Rp.data + " ");                Rp = Rp.right;            }            document.write("<br/>");            Dp = Dp.down;        }    }     // driver program             // 2D matrix        var arr = [ [ 1, 2, 3 ],                    [ 4, 5, 6 ],                    [ 7, 8, 9 ] ];         var m = 3, n = 3;        var head = construct(arr, 0, 0, m, n);        display(head); // This code contributed by Rajput-Ji </script>
Output:  
1 2 3 
4 5 6 
7 8 9
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
princiraj1992
abhaysingh290895
Rajput-Ji
FactSet
Linked List
Matrix
FactSet
Linked List
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
LinkedList in Java
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)