Construct a linked list from 2D matrix (Iterative Approach) in C++


Suppose we have one matrix, we have to convert it to 2d linked list using iterative approach. The list will have the right and down pointer.

So, if the input is like

102030
405060
708090

then the output will be

To solve this, we will follow these steps −

  • real_head := NULL

  • Define an array head_arr of size: m.

  • for initialize i := 0, when i < m, update (increase i by 1), do −

    • head_arr[i] := NULL

    • for initialize j := 0, when j < n, update (increase j by 1), do −

      • p := new tree node with value mat[i, j]

      • if real_head is null, then −

        • real_head := p

      • if head_arr[i] is null, then −

        • head_arr[i] := p

      • Otherwise

        • right of right_ptr := p

      • right_ptr := p

  • for initialize i := 0, when i < m - 1, update (increase i by 1), do −

    • p := head_arr[i], q = head_arr[i + 1]

    • while (p and q both are not null), do −

      • down of p := q

      • p := right of p

      • q := right of q

  • return real_head

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class TreeNode {
   public:
   int data;
   TreeNode *right, *down;
   TreeNode(int d){
      data = d;
      right = down = NULL;
   }
};
void show_2d_list(TreeNode* head) {
   TreeNode *right_ptr, *down_ptr = head;
   while (down_ptr) {
      right_ptr = down_ptr;
      while (right_ptr) {
         cout << right_ptr->data << " ";
         right_ptr = right_ptr->right;
      }
      cout << endl;
      down_ptr = down_ptr->down;
   }
}
TreeNode* make_2d_list(int mat[][3], int m, int n) {
   TreeNode* real_head = NULL;
   TreeNode* head_arr[m];
   TreeNode *right_ptr, *p;
   for (int i = 0; i < m; i++) {
      head_arr[i] = NULL;
      for (int j = 0; j < n; j++) {
         p = new TreeNode(mat[i][j]);
         if (!real_head)
            real_head = p;
         if (!head_arr[i])
            head_arr[i] = p;
         else
            right_ptr->right = p;
         right_ptr = p;
      }
   }
   for (int i = 0; i < m - 1; i++) {
      TreeNode *p = head_arr[i], *q = head_arr[i + 1];
      while (p && q) {
         p->down = q;
         p = p->right;
         q = q->right;
      }
   }
   return real_head;
}
int main() {
   int m = 3, n = 3;
   int mat[][3] = {
      { 10, 20, 30 },
      { 40, 50, 60 },
      { 70, 80, 90 } };
   TreeNode* head = make_2d_list(mat, m, n);
   show_2d_list(head);
}

Input

{ { 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 } }

Output

10 20 30
40 50 60
70 80 90

Updated on: 27-Aug-2020

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements