Open In App

Construct a linked list from 2D matrix

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a matrix. Convert it into a linked list matrix such that each node is connected to its next right and down node.

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

Approach: The problem can be solved based on the following idea:

Connect every cell to its right cell of the same row and to its bottom cell in the same column and also for each cell and keep track of those created node. 

Follow the steps mentioned below to solve this problem:

  • First create a variable of Node type, which will store address of its right and bottom Node corresponding to cell in the matrix.
  • Recursively do the following steps for any cell in the matrix:
    • If Node is not created for any corresponding cell in the matrix, then create a new Node and store it.
    • Else we reach at some cell which has already been created for its corresponding cell in the matrix then return that stored Node.
    • Attach Node to its right and bottom cell which is created and return the current Node.
  • Finally return the root Node.

Below is the implementation of the above approach:

C++




// CPP program to construct a linked list
// from given 2D matrix
#include <bits/stdc++.h>
using namespace std;
// struct node of linked list
struct Node {
    int data;
    Node *right, *down;
};
// returns head pointer of linked list
// constructed from 2D matrix
Node* construct(int arr[][4], int i, int j, int m, int n,
                vector<vector<Node*> >& visited)
{
    // return if i or j is out of bounds
    if (i > m - 1 || j > n - 1)
        return NULL;
    // Check if node is previously created then,
    // don't need to create new/
    if (visited[i][j]) {
        return visited[i][j];
    }
    // create a new node for current i and j
    // and recursively allocate its down and
    // right pointers
    Node* temp = new Node();
    visited[i][j] = temp;
    temp->data = arr[i][j];
    temp->right = construct(arr, i, j + 1, m, n, visited);
    temp->down = construct(arr, i + 1, j, m, n, visited);
    return temp;
}
// utility function for displaying
// linked list data
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) {
        Rp = Dp;
        // loop till node->right is not NULL
        while (Rp) {
            cout << Rp->data << " ";
            Rp = Rp->right;
        }
        cout << "\n";
        Dp = Dp->down;
    }
}
// driver program
int main()
{
    // 2D matrix
    int arr[][4] = { { 1, 2, 3, 0 },
                     { 4, 5, 6, 1 },
                     { 7, 8, 9, 2 },
                     { 7, 8, 9, 2 } };
    int m = 4, n = 4;
    vector<vector<Node*> > visited(m, vector<Node*>(n));
    Node* head = construct(arr, 0, 0, m, n, visited);
    display(head);
    return 0;
}


Java




// Java program to construct a linked list
// from given 2D matrix
public 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, Node[][] visited)
    {
        // return if i or j is out of bounds
        if (i > m - 1 || j > n - 1)
            return null;
        // Check if node is previously created then,
        // don't need to create new/
        if (visited[i][j] != null) {
            return visited[i][j];
        }
        // create a new node for current i and j
        // and recursively allocate its down and
        // right pointers
        Node temp = new Node();
        visited[i][j] = temp;
        temp.data = arr[i][j];
        temp.right
            = construct(arr, i, j + 1, m, n, visited);
        temp.down = construct(arr, i + 1, j, m, n, visited);
        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, 0 },
                        { 4, 5, 6, 1 },
                        { 7, 8, 9, 2 },
                        { 7, 8, 9, 2 } };
        int m = 4, n = 4;
        // List<List<Node>> arr = new
        // ArrayList<List<Node>>();
        Node[][] visited = new Node[m][n];
        Node head = construct(arr, 0, 0, m, n, visited);
        display(head);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python program to construct a linked list
# from given 2D matrix
 
# Node class to represent a node in the linked list
class Node:
    def __init__(self, data=None, right=None, down=None):
        self.data = data
        self.right = right
        self.down = down
 
# Function to construct the linked list from the given 2D matrix
def construct(arr, i, j, m, n, visited):
    # Return if i or j is out of bounds
    if i > m - 1 or j > n - 1:
        return None
 
    # Check if node is previously created, then don't create new
    if visited[i][j]:
        return visited[i][j]
 
    # Create a new node for current i and j and
    # recursively allocate its down and right pointers
    node = Node(arr[i][j])
    visited[i][j] = node
    node.right = construct(arr, i, j + 1, m, n, visited)
    node.down = construct(arr, i + 1, j, m, n, visited)
 
    return node
 
# Utility function for displaying linked list data
def display(head):
    # Pointer to move right
    Rp = head
    # 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 program
if __name__ == "__main__":
    # 2D matrix
    arr = [[1, 2, 3, 0],
           [4, 5, 6, 1],
           [7, 8, 9, 2],
           [7, 8, 9, 2]]
    m = 4
    n = 4
    visited = [[None] * n for _ in range(m)]
    head = construct(arr, 0, 0, m, n, visited)
    display(head)


C#




// C#  program to construct a linked list
// from given 2D matrix
using System;
using System.Collections.Generic;
 
// node of linked list
class Node {
  public int data;
  public Node right;
  public Node down;
}
 
class Linked_list_2D_Matrix
{
 
  // returns head pointer of linked list
  // constructed from 2D matrix
  static Node construct(int[, ] arr, int i, int j, int m,
                        int n, Node[, ] visited)
  {
    // return if i or j is out of bounds
    if (i > m - 1 || j > n - 1)
      return null;
 
    // Check if node is previously created then,
    // don't need to create new/
    if (visited[i, j] != null) {
      return visited[i, j];
    }
 
    // create a new node for current i and j
    // and recursively allocate its down and
    // right pointers
    Node temp = new Node();
    visited[i, j] = temp;
    temp.data = arr[i, j];
    temp.right
      = construct(arr, i, j + 1, m, n, visited);
    temp.down = construct(arr, i + 1, j, m, n, visited);
    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(string[] args)
  {
 
    // 2D matrix
    int[, ] arr = { { 1, 2, 3, 0 },
                   { 4, 5, 6, 1 },
                   { 7, 8, 9, 2 },
                   { 7, 8, 9, 2 } };
    int m = 4, n = 4;
 
    // List<List<Node>> arr = new
    // ArrayList<List<Node>>();
    Node[, ] visited = new Node[m, n];
    Node head = construct(arr, 0, 0, m, n, visited);
    display(head);
  }
}
 
// This code is contributed by phasing17


Javascript




// Javascript program to construct a linked list
      // from given 2D matrix
 
      //node of linked list
      class Node {
        constructor() {
          this.data;
          this.right;
          this.down;
        }
      }
      // returns head pointer of linked list
      // constructed from 2D matrix
      function construct(arr, i, j, m, n, visited) {
        // return if i or j is out of bounds
        if (i > m - 1 || j > n - 1) return null;
        // Check if node is previously created then,
        // don't need to create new/
        if (visited[i][j]) {
          return visited[i][j];
        }
        // create a new node for current i and j
        // and recursively allocate its down and
        // right pointers
        let temp = new Node();
        visited[i][j] = temp;
        temp.data = arr[i][j];
        temp.right = construct(arr, i, j + 1, m, n, visited);
        temp.down = construct(arr, i + 1, j, m, n, visited);
        return temp;
      }
      // utility function for displaying
      // linked list data
      function display(head) {
        // pointer to move right
        let Rp;
        // pointer to move down
        let Dp = head;
        // loop till node.down is not NULL
        while (Dp) {
          Rp = Dp;
          // loop till node.right is not NULL
          while (Rp) {
            console.log(Rp.data + " ");
            Rp = Rp.right;
          }
 
          Dp = Dp.down;
        }
      }
      // driver program
 
      // 2D matrix
      var arr = [
        [1, 2, 3, 0],
        [4, 5, 6, 1],
        [7, 8, 9, 2],
        [7, 8, 9, 2],
      ];
      let m = 4,
        n = 4;
      let visited = Array.from(Array(m), () => new Array(n));
      var head = construct(arr, 0, 0, m, n, visited);
      display(head);


Output

1 2 3 0 
4 5 6 1 
7 8 9 2 
7 8 9 2 
 

Time complexity: O(N*M), where N is the number of row and M is the number of column.
Auxiliary space: O(N*M)

Use a pre-allocated array of nodes instead of allocating new nodes:

This will reduce the overhead of dynamic memory allocation and deallocation, which can be significant in some cases. The nodeCounter variable keeps track of the next available node in the array. A sentinel node is used to simplify the linked list construction logic, and eliminates the need for special cases when creating the first node.

Here is an example implementation that incorporates these optimizations:

C++




#include <bits/stdc++.h>
using namespace std;
 
const int MAXN = 100;
 
struct Node
{
    int data;
    Node *next;
};
 
Node nodes[MAXN];
int nodeCounter = 0;
 
Node *constructLinkedList(int matrix[][4], int rows, int columns)
{
    Node *sentinel = &nodes[nodeCounter++];
    sentinel->next = NULL;
    Node *current = sentinel;
 
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            Node *newNode = &nodes[nodeCounter++];
            newNode->data = matrix[i][j];
            newNode->next = NULL;
 
            current->next = newNode;
            current = current->next;
        }
    }
 
    return sentinel->next;
}
 
void printLinkedList(Node *head)
{
    while (head != NULL)
    {
        cout << head->data << " ";
        head = head->next;
    }
    cout << endl;
}
 
int main()
{
    int matrix[3][4] = {{1, 2, 3, 4},
                        {5, 6, 7, 8},
                        {9, 10, 11, 12}};
 
    Node *head = constructLinkedList(matrix, 3, 4);
    printLinkedList(head);
 
    return 0;
}


Java




// Java code to implement the approach
 
import java.util.*;
 
// Node class definition
class Node {
    public int data;
    public Node next;
}
 
// LinkedListFromMatrix class definition
class LinkedListFromMatrix {
 
    // This method constructs a linked list from a 2D array
    static Node constructLinkedList(int[][] matrix,
                                    int rows, int columns)
    {
        Node sentinel = new Node();
        sentinel.next = null;
        Node current = sentinel;
 
        // Iterating over the rows
        for (int i = 0; i < rows; i++) {
            // Iterating over the columns
            for (int j = 0; j < columns; j++) {
                // Adding node to linked list
                Node newNode = new Node();
                newNode.data = matrix[i][j];
                newNode.next = null;
 
                current.next = newNode;
                current = current.next;
            }
        }
 
        return sentinel.next;
    }
 
    // This function displays the linked list
    static void printLinkedList(Node head)
    {
        while (head != null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
        System.out.println(" ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[][] matrix = new int[][] { { 1, 2, 3, 4 },
                                       { 5, 6, 7, 8 },
                                       { 9, 10, 11, 12 } };
 
        // Function calls
        Node head = constructLinkedList(matrix, 3, 4);
        printLinkedList(head);
    }
}


C#




// C# code to implement the approach
 
using System;
 
// Node class definition
class Node
{
    public int data;
    public Node next;
}
 
class LinkedListFromMatrix
{
    // This function constructs a linked list from a 2D array
    static Node ConstructLinkedList(int[,] matrix, int rows, int columns)
    {
        Node sentinel = new Node();
        sentinel.next = null;
        Node current = sentinel;
         
        // Iterating over the rows
        for (int i = 0; i < rows; i++)
        {
            // Iterating over the columns
            for (int j = 0; j < columns; j++)
            {
                // Adding node to linked list
                Node newNode = new Node();
                newNode.data = matrix[i, j];
                newNode.next = null;
 
                current.next = newNode;
                current = current.next;
            }
        }
 
        return sentinel.next;
    }
     
    // This function prints the linked list
    static void PrintLinkedList(Node head)
    {
        while (head != null)
        {
            Console.Write(head.data + " ");
            head = head.next;
        }
        Console.WriteLine(" ");
    }
     
    // Driver code
    static void Main(string[] args)
    {
        int[,] matrix = new int[3, 4] {{1, 2, 3, 4},
                                       {5, 6, 7, 8},
                                       {9, 10, 11, 12}};
         
        // Function calls
        Node head = ConstructLinkedList(matrix, 3, 4);
        PrintLinkedList(head);
    }
}


Python3




# GFG
# Python program to construct a linked list
# from given 2D matrix
# Pre-allocated array of nodes instead of allocating new nodes
 
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None
 
 
def construct_linked_list(matrix):
    sentinel = Node()
    current = sentinel
 
    for row in matrix:
        for element in row:
            new_node = Node(element)
            current.next = new_node
            current = current.next
 
    return sentinel.next
 
 
def print_linked_list(head):
    while head is not None:
        print(head.data, end=" ")
        head = head.next
    print()
 
 
if __name__ == "__main__":
    matrix = [[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12]]
 
    head = construct_linked_list(matrix)
    print_linked_list(head)
# This code is written by Sundaram


Javascript




// Javascript program to construct a linked list
// from given 2D matrix
// Pre-allocated array of nodes instead of allocating new nodes
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
function constructLinkedList(matrix) {
    const sentinel = new Node();
    let current = sentinel;
    for (const row of matrix) {
        for (const element of row) {
            const newNode = new Node(element);
            current.next = newNode;
            current = current.next;
        }
    }
 
    return sentinel.next;
}
 
function printLinkedList(head) {
    let currentNode = head;
    let temp = []
    while (currentNode !== null) {
        temp.push(currentNode.data);
        currentNode = currentNode.next;
    }
    console.log(temp.join(' '));
}
 
const matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
];
 
const head = constructLinkedList(matrix);
printLinkedList(head);
 
// Contributed by adityasharmadev01


Output

1 2 3 4 5 6 7 8 9 10 11 12 

Time complexity: O(N*M)
Auxiliary space: O(N*M)

 



Last Updated : 01 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads