Construct a linked list from 2D matrix (Iterative Approach)
Last Updated : 26 Sep, 2024
Given a Matrix mat of n*n size, the task is to construct a 2D linked list representation of the given matrix.
Example:
Input : mat = [[1 2 3]
[4 5 6]
[7 8 9]]
Output :
Input : mat = [[23 28]
[23 28]]
Output :
Approach:
To Construct a linked list from 2D matrix iteratively follow the steps below:
- The idea is to create m linked lists (m = number of rows) whose each node stores its right node. The head pointers of each m linked lists are stored in an array of nodes.
- Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each node of ith list to its corresponding node of (i+1)th list.
Construct a linked list from 2D matrix
Below is the implementation of the above approach:
C++ // C++ to implement linked matrix // from a 2D matrix iteratively #include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *right, *down; Node(int x) { data = x; right = down = nullptr; } }; // Function to construct the linked list from the given /// matrix and return the head pointer Node* constructLinkedMatrix(vector<vector<int>>& mat) { int m = mat.size(); int n = mat[0].size(); // Stores the head of the linked list Node* mainhead = nullptr; // Stores the head of linked lists of each row vector<Node*> head(m); Node *rightcurr, *newptr; // Create m linked lists by setting all // the right nodes of every row for (int i = 0; i < m; i++) { head[i] = nullptr; for (int j = 0; j < n; j++) { newptr = new Node(mat[i][j]); // Assign the first node as the mainhead if (!mainhead) { mainhead = newptr; } // Set the head for the row or link // the current node if (!head[i]) { head[i] = newptr; } else { rightcurr->right = newptr; } rightcurr = newptr; } } // Set the down pointers for nodes in consecutive rows for (int i = 0; i < m - 1; i++) { Node *curr1 = head[i], *curr2 = head[i + 1]; // Link corresponding nodes in consecutive rows while (curr1 && curr2) { curr1->down = curr2; curr1 = curr1->right; curr2 = curr2->right; } } // Return the mainhead of the constructed // linked list return mainhead; } void printList(Node *head) { Node *currRow = head; while (currRow != nullptr) { Node *currCol = currRow; while (currCol != nullptr) { cout << currCol->data << " "; currCol = currCol->right; } cout << endl; currRow = currRow->down; } } int main() { vector<vector<int>> mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node* head = constructLinkedMatrix(mat); printList(head); return 0; }
Java // Java to implement linked matrix // from a 2D matrix iteratively import java.util.ArrayList; class Node { int data; Node right, down; Node(int data) { this.data = data; this.right = null; this.down = null; } } class GfG { // Function to construct the linked // matrix from a 2D array static Node construct(int arr[][]) { int m = arr.length; int n = arr[0].length; // Stores the head of the linked list Node mainhead = null; // ArrayList to store the heads of // linked lists for each row ArrayList<Node> head = new ArrayList<>(m); Node rightcurr = null; // Create m linked lists by setting all // the right nodes of every row for (int i = 0; i < m; i++) { head.add(null); for (int j = 0; j < n; j++) { Node newptr = new Node(arr[i][j]); // Assign the first node as the mainhead if (mainhead == null) { mainhead = newptr; } // Set the head for the row or link // the current node if (head.get(i) == null) { head.set(i, newptr); } else { rightcurr.right = newptr; } rightcurr = newptr; } } // Set the down pointers for nodes in // consecutive rows for (int i = 0; i < m - 1; i++) { Node curr1 = head.get(i); Node curr2 = head.get(i + 1); // Link corresponding nodes in consecutive rows while (curr1 != null && curr2 != null) { curr1.down = curr2; curr1 = curr1.right; curr2 = curr2.right; } } // Return the mainhead of the constructed // linked list return mainhead; } static void printList(Node head) { Node currRow = head; while (currRow != null) { Node currCol = currRow; while (currCol != null) { System.out.print(currCol.data + " "); currCol = currCol.right; } System.out.println(); currRow = currRow.down; } } public static void main(String[] args) { int arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; Node head = construct(arr); printList(head); } }
Python # Python to implement linked matrix # from a 2D matrix iteratively class Node: def __init__(self, data): self.data = data self.right = None self.down = None def constructLinkedMatrix(mat): m = len(mat) n = len(mat[0]) # Stores the head of the linked list mainhead = None # Stores the head of linked lists of each row head = [None] * m rightcurr = None # Create m linked lists by setting all the # right nodes of every row for i in range(m): head[i] = None for j in range(n): newptr = Node(mat[i][j]) # Assign the first node as the mainhead if not mainhead: mainhead = newptr # Set the head for the row or link the # current node if not head[i]: head[i] = newptr else: rightcurr.right = newptr rightcurr = newptr # Set the down pointers for nodes in consecutive rows for i in range(m - 1): curr1 = head[i] curr2 = head[i + 1] # Link corresponding nodes in consecutive rows while curr1 and curr2: curr1.down = curr2 curr1 = curr1.right curr2 = curr2.right # Return the mainhead of the constructed linked list return mainhead def printList(head): currRow = head while currRow: currCol = currRow while currCol: print(currCol.data, end=" ") currCol = currCol.right print() currRow = currRow.down if __name__ == "__main__": mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] head = constructLinkedMatrix(mat) printList(head)
C# // C# to implement linked matrix // from a 2D matrix iteratively using System; using System.Collections.Generic; class Node { public int data; public Node right, down; public Node(int x) { data = x; right = down = null; } } class GfG { // Function to construct the linked matrix // from a List of Lists static Node Construct(List<List<int>> arr) { int m = arr.Count; int n = arr[0].Count; // Stores the head of the linked list Node mainhead = null; // List to store the heads of linked // lists for each row List<Node> head = new List<Node>(m); Node rightcurr = null; // Create m linked lists by setting all the // right nodes of every row for (int i = 0; i < m; i++) { head.Add(null); for (int j = 0; j < n; j++) { Node newptr = new Node(arr[i][j]); // Assign the first node as the mainhead if (mainhead == null) { mainhead = newptr; } // Set the head for the row or link // the current node if (head[i] == null) { head[i] = newptr; } else { rightcurr.right = newptr; } rightcurr = newptr; } } // Set the down pointers for nodes // in consecutive rows for (int i = 0; i < m - 1; i++) { Node curr1 = head[i]; Node curr2 = head[i + 1]; // Link corresponding nodes in // consecutive rows while (curr1 != null && curr2 != null) { curr1.down = curr2; curr1 = curr1.right; curr2 = curr2.right; } } // Return the mainhead of the // constructed linked list return mainhead; } static void PrintList(Node head) { Node currRow = head; while (currRow != null) { Node currCol = currRow; while (currCol != null) { Console.Write(currCol.data + " "); currCol = currCol.right; } Console.WriteLine(); currRow = currRow.down; } } static void Main(string[] args) { List<List<int>> arr = new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 }, new List<int> { 7, 8, 9 } }; Node head = Construct(arr); PrintList(head); } }
JavaScript // Javascript to implement linked matrix // from a 2D matrix iteratively class Node { constructor(data) { this.data = data; this.right = null; this.down = null; } } // Function to construct the linked matrix // from a 2D array function constructLinkedMatrix(arr) { const m = arr.length; const n = arr[0].length; // Stores the head of the linked list let mainHead = null; // Array to store the heads of linked // lists for each row const head = new Array(m).fill(null); let rightCurr = null; // Create m linked lists by setting all the // right nodes of every row for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { const newPtr = new Node(arr[i][j]); // Assign the first node as the mainHead if (mainHead === null) { mainHead = newPtr; } // Set the head for the row or // link the current node if (head[i] === null) { head[i] = newPtr; } else { rightCurr.right = newPtr; } rightCurr = newPtr; } } // Set the down pointers for nodes in // consecutive rows for (let i = 0; i < m - 1; i++) { let curr1 = head[i]; let curr2 = head[i + 1]; // Link corresponding nodes in consecutive rows while (curr1 && curr2) { curr1.down = curr2; curr1 = curr1.right; curr2 = curr2.right; } } // Return the mainHead of the constructed // linked list return mainHead; } function printList(head) { let currRow = head; while (currRow !== null) { let currCol = currRow; while (currCol !== null) { console.log(currCol.data + " "); currCol = currCol.right; } console.log(); currRow = currRow.down; } } const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; const head = constructLinkedMatrix(arr); printList(head);
Time Complexity: O(n^2), where n is the number of rows and columns in the matrix. This is because we need to traverse each element of the matrix exactly once to create the linked list nodes.
Space Complexity: O(n^2), for storing the linked list nodes since we are creating a new node for each element in the matrix.
Related articles:
Similar Reads
Construct a linked list from 2D matrix Given a Matrix mat of n*n size, the task is to construct a 2D linked list representation of the given matrix. Example:Input : mat = [[1 2 3] [4 5 6] [7 8 9]]Output : Input : mat = [[23 28] [23 28]]Output : Table of Content[Expected Approach - 1] Recursive Approach - O(n^2) Time and O(n^2) Space[Expe
8 min read
Construct a Doubly linked linked list from 2D Matrix Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to con
15+ min read
Create linked list from a given array Given an array arr[] of size N. The task is to create linked list from the given array.Examples: Input : arr[] = {1, 2, 3, 4, 5}Output : 1->2->3->4->5Input :arr[] = {10, 11, 12, 13, 14}Output : 10->11->12->13->14Simple Approach: For each element of an array arr[] we create a
8 min read
Construct Ancestor Matrix from a Given Binary Tree Given a Binary Tree where all values are from 0 to n-1. Construct an ancestor matrix mat[n][n] where the ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of jmat[i][j] = 0, otherwiseExamples: Input: Output: {{0 1 1} {0 0 0} {0 0 0}}Input: Output: {{0 0 0 0 0 0} {1 0 0 0 1 0} {0 0
15+ min read
Iterative approach for removing middle points in a linked list of line segments This post explains the iterative approach of this problem. We maintain two pointers, prev and temp. If these two have either x or y same, we move forward till the equality holds and keep deleting the nodes in between. The node from which the equality started, we adjust the next pointer of that node.
9 min read