Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Construct a linked list from 2D matrix (Iterative Approach)
Next article icon

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

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :

Construct-a-linked-list-from-2D-matrix-1


Input : mat = [[23 28]
[23 28]]
Output :

Construct-a-linked-list-from-2D-matrix-2

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-3
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); 

Output
1 2 3  4 5 6  7 8 9 

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:

  • Construct a linked list from 2D matrix

Next Article
Construct a linked list from 2D matrix (Iterative Approach)

S

souravdutta123
Improve
Article Tags :
  • Linked List
  • DSA
Practice Tags :
  • Linked List

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences