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

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

10 20 30
40 50 60
70 80 90

then the output will be

To solve this, we will follow these steps −

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
Arnab Chakraborty
Updated on: 2020-08-27T14:18:10+05:30