

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct a linked list from 2D matrix in C++
Suppose we have one matrix, we have to convert it to 2d linked list using recursive 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 −
Define a function make_2d_list(), this will take matrix mat, i, j, m, n,
if i and j are not in the matrix boundary, then −
return null
temp := create a new node with value mat[i, j]
right of temp := make_2d_list(mat, i, j + 1, m, n)
down of temp := make_2d_list(mat, i + 1, j, m, n)
return temp
Example
Let us see the following implementation to get better understanding −
#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 i, int j, int m, int n) { if (i > n - 1 || j > m - 1) return NULL; TreeNode* temp = new TreeNode(mat[i][j]); temp->right = make_2d_list(mat, i, j + 1, m, n); temp->down = make_2d_list(mat, i + 1, j, m, n); return temp; } 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, 0, 0, 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
- Related Questions & Answers
- Construct a linked list from 2D matrix (Iterative Approach) in C++
- Search a 2D Matrix in C++
- Program to find linked list intersection from two linked list in Python
- Maximum sum rectangle in a 2D matrix
- Search a 2D Matrix II in Python
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes in Python
- Remove elements from a linked list using Javascript
- Print a 2D Array or Matrix in Java
- Program to find folded list from a given linked list in Python
- Check if a linked list is Circular Linked List in C++
- Removing Elements from a Double Linked List using Javascript
- Create linked list from a given array in C++ Program
- Remove elements from singly linked list in JavaScript
- How to remove duplicates from a sorted linked list in android?
- Delete a Node from linked list without head pointer in C++
Advertisements