Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix

Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix.
Examples:
Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}
Output:
Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ? (2, 2, 2) ? (1, 1, 1) ? (0, 1, 1) ? NULL
Original matrix:
{{0, 1, 0, 0, 0},Â
{0, 1, 0, 0, 0},Â
{0, 0, 2, 0, 0},Â
{0, 3, 0, 0, 4}
{0, 0, 5, 0, 0}}Input: mat[][] = {{0, 0, 0, 4, 0}, {0, 1, 0, 0, 0}}
Output:
Linked list representation: (1, 1, 1) ? (0, 3, 4) ? NULL
Original matrix:
{{0, 0, 0, 4, 0},Â
{0, 1, 0, 0, 0}}
Approach: The given problem can be solved by storing the row index, column index, its value, and the next pointer of all non-zero elements in the node of the linked list. Follow the steps below to solve the problem:Â
- For the construction of the sparse matrix using a linked list, traverse the matrix, and for every non-zero element create a new node and insert this newly created node to the beginning of the list.
- For the reconstruction, create an auxiliary 2D array of dimensions N*M with all entries as 0, then traverse the linked list and update all the non-zero elements in this newly created array.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <iostream>#include <vector>Â
using namespace std;Â
// Linked list nodestruct SNode {Â Â Â Â int data;Â Â Â Â int Col;Â Â Â Â int Row;Â Â Â Â SNode* next;};Â
// Store the head pointer of the linked list// and the size of the matrixstruct MatrixNode {Â Â Â Â vector<vector<int> > Matrix;Â Â Â Â SNode* SNPTR;};Â
// Function to create a new nodeSNode* CreateList(int Row, int Col, int data){Â
    // Create a new node    SNode* New = new SNode();Â
    // Update the value and the row    // and column index and set the    // next pointer to NULL    New->data = data;    New->Col = Col;    New->Row = Row;    New->next = NULL;Â
    return New;}Â
// Function to insert a node at the// beginning of the linked listMatrixNode* AddInList(MatrixNode* MNhead, int Row, int Col,                      int data){    MatrixNode* Mptr = MNhead;Â
    // Create a new node    SNode* New = CreateList(Row, Col, data);Â
    // If the head is NULL, point it to the newly    // created node    if (Mptr->SNPTR == NULL) {        Mptr->SNPTR = New;        return MNhead;    }Â
    // Insert this node at beginning    New->next = Mptr->SNPTR;Â
    // Update the head pointer    Mptr->SNPTR = New;Â
    return MNhead;}Â
// Function to construct the sparse// matrix using linked listMatrixNode*ConstructSparseMatrix(MatrixNode* MNhead,                      vector<vector<int> > Matrix,                      SNode* SNhead){    MatrixNode* Mptr = MNhead;Â
    // If the head pointer is NULL    if (MNhead == NULL) {        MNhead = new MatrixNode();        MNhead->Matrix = Matrix;        MNhead->SNPTR = SNhead;    }Â
    Mptr = MNhead;Â
    // Traverse the matrix, row-wise    for (int i = 0; i < Mptr->Matrix.size(); i++) {        for (int j = 0; j < Mptr->Matrix[i].size(); j++) {            // For all non-zero values, push them in linked            // list            if (Matrix[i][j] != 0)                MNhead                    = AddInList(MNhead, i, j, Matrix[i][j]);        }    }    return MNhead;}Â
// Function to reconstruct the sparse// matrix using linked listvoid ReConstructArray(MatrixNode* MNhead){Â Â Â Â int i, j;Â Â Â Â SNode* Sptr = MNhead->SNPTR;Â
    // Create a 2D array    vector<vector<int> > OriginalMatrix(        MNhead->Matrix.size(),        vector<int>(MNhead->Matrix[0].size()));Â
    // Initialize all the elements in the original matrix as    // 0    for (i = 0; i < MNhead->Matrix.size(); i++) {        for (j = 0; j < MNhead->Matrix[i].size(); j++) {            OriginalMatrix[i][j] = 0;        }    }Â
    // Print the linked list representation:    cout << "Linked list representation:" << endl;Â
    // Iterate while sptr pointer is not NULL    while (Sptr != NULL) {        // Update the element in the original matrix and        // print the current node:        OriginalMatrix[Sptr->Row][Sptr->Col] = Sptr->data;        cout << "(" << Sptr->Row << ", " << Sptr->Col             << ", " << OriginalMatrix[Sptr->Row][Sptr->Col]             << ")->";        // Move to the next node:        Sptr = Sptr->next;    }    cout << "NULL" << endl;Â
    // Print the original matrix    cout << "Original Matrix Re-Construction:" << endl;    for (i = 0; i < MNhead->Matrix.size(); i++) {        for (j = 0; j < MNhead->Matrix[i].size(); j++) {            cout << OriginalMatrix[i][j] << ", ";        }        cout << endl;    }}Â
int main(){    // Initialize the head pointer of the linked list    MatrixNode* MNhead = NULL;    SNode* SNhead = NULL;Â
    // Create the dense matrix    vector<vector<int> > Matrix = { { 0, 1, 0, 0, 0 },                                    { 0, 1, 0, 0, 0 },                                    { 0, 0, 2, 0, 0 },                                    { 0, 3, 0, 0, 4 },                                    { 0, 0, 5, 0, 0 } };Â
    // Construct the sparse matrix    MNhead = ConstructSparseMatrix(MNhead, Matrix, SNhead);Â
    // Reconstruct the original matrix    ReConstructArray(MNhead);Â
    return 0;}Â
// This code is contributed by lokeshmvs21. |
C
// C program for the above approachÂ
#include <stdio.h>#include <stdlib.h>Â
// Store the size of sparse matrix#define R 5#define C 5Â
// Linked list nodetypedef struct SNode {Â Â Â Â int data;Â Â Â Â int Col;Â Â Â Â int Row;Â Â Â Â struct SNode* next;} SparseNode;Â
// Store the head pointer of the linked// list and the size of the matrixtypedef struct MNode {Â Â Â Â int Matrix[2];Â Â Â Â SparseNode* SNPTR;} MatrixNode;Â
// Function to initialize the head of// the linked listMatrixNode* ConstructMNhead(Â Â Â Â MatrixNode* MNhead, SparseNode* SNhead){Â
    MNhead = (MatrixNode*)malloc(sizeof(MNhead));Â
    // Update the number of rows and    // columns and update head pointer    MNhead->Matrix[0] = R;    MNhead->Matrix[1] = C;    MNhead->SNPTR = SNhead;Â
    return MNhead;}Â
// Function to create a new nodeSparseNode* CreateList(int Row, int Col,                       int data){Â
    // Create a new node    SparseNode* New        = (SparseNode*)malloc(sizeof(SparseNode));Â
    // Update the value and the row    // and column index and set the    // next pointer to NULL    New->data = data;    New->Col = Col;    New->Row = Row;    New->next = NULL;Â
    return New;}Â
// Function to insert a node at the// beginning of the linked listMatrixNode* AddInList(    MatrixNode* MNhead, int Row,    int Col, int data){    MatrixNode* Mptr = MNhead;Â
    // Create a new node    SparseNode* New = CreateList(        Row, Col, data);Â
    // If the head is NULL, point it    // to the newly created node    if (Mptr->SNPTR == NULL) {        Mptr->SNPTR = New;        return MNhead;    }Â
    // Insert this node at beginning    New->next = Mptr->SNPTR;Â
    // Update the head pointer    Mptr->SNPTR = New;Â
    return MNhead;}Â
// Function to construct the sparse// matrix using linked listMatrixNode* ConstructSparseMatrix(    MatrixNode* MNhead, int Matrix[R][C],    SparseNode* SNhead){    int i, j;    MatrixNode* Mptr = MNhead;Â
    // If the head pointer is NULL    if (MNhead == NULL) {        MNhead = ConstructMNhead(            MNhead, SNhead);    }Â
    Mptr = MNhead;Â
    // Traverse the matrix, row-wise    for (i = 0;         i < Mptr->Matrix[0]; i++) {        for (j = 0;             j < Mptr->Matrix[1]; j++) {Â
            // For all non-zero values,            // push them in linked list            if (Matrix[i][j])                MNhead = AddInList(                    MNhead, i, j,                    Matrix[i][j]);        }    }Â
    return MNhead;}Â
// Function to reconstruct the sparse// matrix using linked listvoid ReConstructArray(MatrixNode* MNhead){Â Â Â Â int i, j;Â Â Â Â SparseNode* Sptr = MNhead->SNPTR;Â
    // Create a 2D array    int** OriginalMatrixÂ
        = (int**)malloc(sizeof(int*)                        * MNhead->Matrix[0]);Â
    for (i = 0;         i < MNhead->Matrix[0]; i++) {        OriginalMatrix[i]            = (int*)malloc(sizeof(int)                           * MNhead->Matrix[1]);    }Â
    // Initialize all the elements    // in the original matrix as 0    for (i = 0;         i < MNhead->Matrix[0]; i++) {Â
        for (j = 0;             j < MNhead->Matrix[1]; j++) {            OriginalMatrix[i][j] = 0;        }    }Â
    // Print the linked list    printf("Linked list represe"           "ntation:\n");Â
    // Iterate while sptr pointer is not NULL    while (Sptr != NULL) {Â
        // Update the element in the        // original matrix and print        // the current node        OriginalMatrix[Sptr->Row][Sptr->Col]            = Sptr->data;Â
        printf("(%d, %d, %d)->",               Sptr->Row, Sptr->Col,               OriginalMatrix[Sptr->Row][Sptr->Col]);Â
        // Move to the next node        Sptr = Sptr->next;    }    printf("NULL\n");Â
    // Print the reconstructed matrix    printf("Original Matrix Re"           "-Construction:\n");Â
    for (i = 0; i < R; i++) {        for (j = 0; j < C; j++) {            printf("%d, ", OriginalMatrix[i][j]);        }        printf("\n");    }}Â
// Create a head of the linked listMatrixNode* MNhead = NULL;SparseNode* SNhead = NULL;Â
// Driver Codeint main(){    int Matrix[R][C] = { { 0, 1, 0, 0, 0 },                         { 0, 1, 0, 0, 0 },                         { 0, 0, 2, 0, 0 },                         { 0, 3, 0, 0, 4 },                         { 0, 0, 5, 0, 0 } };    int** OriginalMatrix;Â
    // Sparse matrix Construction    MNhead = ConstructSparseMatrix(        MNhead, Matrix, SNhead);Â
    // Sparse matrix Re-Construction    ReConstructArray(MNhead);Â
    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class Main{       // Store the size of sparse matrix    static int R = 5;    static int C = 5;Â
    // Function to initialize the head of    // the linked list    public static MatrixNode    ConstructMNhead(MatrixNode MNhead, SparseNode SNhead)    {        MNhead = new MatrixNode();Â
        // Update the number of rows and        // columns and update head pointer        MNhead.Matrix[0] = R;        MNhead.Matrix[1] = C;        MNhead.SNPTR = SNhead;        return MNhead;    }Â
    // Function to create a new node    public static SparseNode CreateList(int Row, int Col,                                        int data)    {        // Create a new node        SparseNode New = new SparseNode();Â
        // Update the value and the row        // and column index and set the        // next pointer to NULL        New.data = data;        New.Col = Col;        New.Row = Row;        New.next = null;Â
        return New;    }Â
    // Function to insert a node at the    // beginning of the linked list    public static MatrixNode    AddInList(MatrixNode MNhead, int Row, int Col, int data)    {        MatrixNode Mptr = MNhead;Â
        // Create a new node        SparseNode New = CreateList(Row, Col, data);Â
        // If the head is NULL, point it to the newly        // created node        if (Mptr.SNPTR == null) {            Mptr.SNPTR = New;            return MNhead;        }Â
        // Insert this node at beginning        New.next = Mptr.SNPTR;Â
        // Update the head pointer        Mptr.SNPTR = New;Â
        return MNhead;    }Â
    // Function to construct the sparse    // matrix using linked list    public static MatrixNode    ConstructSparseMatrix(MatrixNode MNhead, int[][] Matrix,                          SparseNode SNhead)    {        int i, j;        MatrixNode Mptr = MNhead;Â
        // If the head pointer is NULL        if (MNhead == null) {            MNhead = ConstructMNhead(MNhead, SNhead);        }Â
        Mptr = MNhead;Â
        // Traverse the matrix, row-wise        for (i = 0; i < Mptr.Matrix[0]; i++) {            for (j = 0; j < Mptr.Matrix[1]; j++) {                // For all non-zero values, push them in                // linked list                if (Matrix[i][j] != 0)                    MNhead = AddInList(MNhead, i, j,                                       Matrix[i][j]);            }        }        return MNhead;    }Â
    // Function to reconstruct the sparse    // matrix using linked list    public static void ReConstructArray(MatrixNode MNhead)    {        int i, j;        SparseNode Sptr = MNhead.SNPTR;Â
        // Create a 2D array        int[][] OriginalMatrix            = new int[MNhead.Matrix[0]][MNhead.Matrix[1]];Â
        // Initialize all the elements in the original        // matrix as 0        for (i = 0; i < MNhead.Matrix[0]; i++) {            for (j = 0; j < MNhead.Matrix[1]; j++) {                OriginalMatrix[i][j] = 0;            }        }Â
        // Print the linked list representation:        System.out.println("Linked list representation:");Â
        // Iterate while sptr pointer is not NULL        while (Sptr != null) {            // Update the element in the original matrix and            // print the current node:            OriginalMatrix[Sptr.Row][Sptr.Col] = Sptr.data;            System.out.print(                "(" + Sptr.Row + ", " + Sptr.Col + ", "                + OriginalMatrix[Sptr.Row][Sptr.Col]                + ")->");            // Move to the next node:            Sptr = Sptr.next;        }        System.out.println("NULL");Â
        // Print the reconstructed matrix        System.out.println(            "Original Matrix Re-Construction:");Â
        for (i = 0; i < R; i++) {            for (j = 0; j < C; j++) {                System.out.print(OriginalMatrix[i][j]                                 + ", ");            }            System.out.println("");        }    }Â
    // Driver Code    public static void main(String[] args)    {        // Create a head of the linked list        MatrixNode MNhead = null;        SparseNode SNhead = null;Â
        int[][] Matrix = { { 0, 1, 0, 0, 0 },                           { 0, 1, 0, 0, 0 },                           { 0, 0, 2, 0, 0 },                           { 0, 3, 0, 0, 4 },                           { 0, 0, 5, 0, 0 } };        int[][] OriginalMatrix;        // Sparse matrix Construction        MNhead            = ConstructSparseMatrix(MNhead, Matrix, SNhead);        // Sparse matrix Re-Construction        ReConstructArray(MNhead);    }}Â
// Linked list nodeclass SparseNode {Â Â Â Â int data;Â Â Â Â int Col;Â Â Â Â int Row;Â Â Â Â SparseNode next;}Â
// Store the head pointer of the linked// list and the size of the matrixclass MatrixNode {Â Â Â Â int[] Matrix = new int[2];Â Â Â Â SparseNode SNPTR;}Â
// This code is contributed by Tapesh (tapeshdua420) |
Python3
# python code for above approachR = 5C = 5Â
# linked list nodeclass SparseNode:       # Function to initialize the node object    def __init__(self, data, Col, Row):        self.data = data # Assign data        self.Col = Col # Assign Column        self.Row = Row # Assign Row        self.next = None # Initialize        # next as nullÂ
# Store the head pointer of the linked# list and the size of the matrixclass MatrixNode:       # Function to initialize the node object    def __init__(self, Matrix, SNPTR):        self.Matrix = Matrix # Initialize matrix        self.SNPTR = None # Initialize        # SNPTR as nullÂ
# Function to initialize the head of# the linked listdef ConstructMNhead(MNhead, SNhead):       # add the number of rows and    # columns and add head pointer    MNhead = MatrixNode([R, C], SNhead)    return MNheadÂ
# Function to create a new nodeÂ
Â
def CreateList(Row, Col, data):    # Create a new node    New = SparseNode(data, Col, Row)    return NewÂ
# Function to insert a node at the# beginning of the linked listdef AddInList(MNhead, Row, Col, data):    Mptr = MNhead    # Create a new node    New = CreateList(Row, Col, data)Â
    # If the head is NULL, point it    # to the newly created node    if (Mptr.SNPTR == None):        Mptr.SNPTR = New        return MNheadÂ
    # Insert this node at beginning    New.next = Mptr.SNPTRÂ
    # Update the head pointer    Mptr.SNPTR = NewÂ
    return MNheadÂ
# Function to construct the sparse# matrix using linked listdef ConstructSparseMatrix(MNhead, Matrix,                          SNhead):    Mptr = MNheadÂ
    # If the head pointer is NULL    if (MNhead == None):        MNhead = ConstructMNhead(            MNhead, SNhead)Â
    Mptr = MNheadÂ
    # Traverse the matrix, row-wise    for i in range(0, Mptr.Matrix[0]):        for j in range(0, Mptr.Matrix[1]):Â
            # For all non-zero values,            # push them in linked list            if (Matrix[i][j]):                MNhead = AddInList(                    MNhead, i, j,                    Matrix[i][j])Â
    return MNheadÂ
# Function to reconstruct the sparse# matrix using linked listdef ReConstructArray(MNhead):Â Â Â Â Sptr = MNhead.SNPTRÂ
    # Create a 2D array    OriginalMatrix = []Â
    # Initialize all the elements    # in the original matrix as 0    for i in range(0, MNhead.Matrix[0]):        OriginalMatrix.append([])        for j in range(0, MNhead.Matrix[1]):            OriginalMatrix[i].append(0)Â
    # Print the linked list    print("Linked list represe"          "ntation:\n")Â
    # Iterate while sptr pointer is not NULL    while (Sptr != None):Â
        # Update the element in the        # original matrix and print        # the current node        OriginalMatrix[Sptr.Row][Sptr.Col] = Sptr.dataÂ
        print("(", Sptr.Row, ",", Sptr.Col, ",",              OriginalMatrix[Sptr.Row][Sptr.Col], ")->", end=" ")Â
        # Move to the next node        Sptr = Sptr.next    print("None\n")Â
    # Print the reconstructed matrix    print("Original Matrix Re"          "-Construction:\n")Â
    for i in range(0, R):        for j in range(0, C):            print(OriginalMatrix[i][j], end=" ")        print("\n")Â
Â
# Create a head of the linked listÂ
# Driver CodeMatrix = [[0, 1, 0, 0, 0],          [0, 1, 0, 0, 0],          [0, 0, 2, 0, 0],          [0, 3, 0, 0, 4],          [0, 0, 5, 0, 0]]Â
MNhead = NoneSNhead = None# Sparse matrix ConstructionMNhead = ConstructSparseMatrix(MNhead, Matrix, SNhead)Â
# Sparse matrix Re-ConstructionReConstructArray(MNhead)Â
# This code is contributed by rj13to |
C#
// C# program for the above approachusing System;Â
class Program {Â
    // Store the size of sparse matrix    static int R = 5;    static int C = 5;Â
    // Function to initialize the head of    // the linked list    public static MatrixNode    ConstructMNhead(MatrixNode MNhead, SparseNode SNhead)    {        MNhead = new MatrixNode();Â
        // Update the number of rows and        // columns and update head pointer        MNhead.Matrix[0] = R;        MNhead.Matrix[1] = C;        MNhead.SNPTR = SNhead;        return MNhead;    }Â
    // Function to create a new node    public static SparseNode CreateList(int Row, int Col,                                        int data)    {        // Create a new node        SparseNode New = new SparseNode();Â
        // Update the value and the row        // and column index and set the        // next pointer to NULL        New.data = data;        New.Col = Col;        New.Row = Row;Â
        return New;    }Â
    // Function to insert a node at the    // beginning of the linked list    public static MatrixNode    AddInList(MatrixNode MNhead, int Row, int Col, int data)    {        MatrixNode Mptr = MNhead;Â
        // Create a new node        SparseNode New = CreateList(Row, Col, data);Â
        // If the head is NULL, point it to the newly        // created node        if (Mptr.SNPTR == null) {            Mptr.SNPTR = New;            return MNhead;        }Â
        // Insert this node at beginning        New.next = Mptr.SNPTR;Â
        // Update the head pointer        Mptr.SNPTR = New;Â
        return MNhead;    }Â
    // Function to construct the sparse    // matrix using linked list    public static MatrixNode    ConstructSparseMatrix(MatrixNode MNhead, int[, ] Matrix,                          SparseNode SNhead)    {        int i, j;        MatrixNode Mptr = MNhead;Â
        // If the head pointer is NULL        if (MNhead == null) {            MNhead = ConstructMNhead(MNhead, SNhead);        }Â
        Mptr = MNhead;Â
        // Traverse the matrix, row-wise        for (i = 0; i < Mptr.Matrix[0]; i++) {            for (j = 0; j < Mptr.Matrix[1]; j++) {                // For all non-zero values, push them in                // linked list                if (Matrix[i, j] != 0)                    MNhead = AddInList(MNhead, i, j,                                       Matrix[i, j]);            }        }        return MNhead;    }Â
    public static void ReConstructArray(MatrixNode MNhead)    {        int i, j;        SparseNode Sptr = MNhead.SNPTR;Â
        // Create a 2D array        int[, ] OriginalMatrix            = new int[MNhead.Matrix[0], MNhead.Matrix[1]];Â
        // Initialize all the elements in the original        // matrix as 0        for (i = 0; i < MNhead.Matrix[0]; i++) {            for (j = 0; j < MNhead.Matrix[1]; j++) {                OriginalMatrix[i, j] = 0;            }        }Â
        // Print the linked list representation:        Console.WriteLine("Linked list representation:");Â
        // Iterate while sptr pointer is not NULL        while (Sptr != null) {            // Update the element in the original matrix and            // print the current node:            OriginalMatrix[Sptr.Row, Sptr.Col] = Sptr.data;            Console.Write(                "(" + Sptr.Row + ", " + Sptr.Col + ", "                + OriginalMatrix[Sptr.Row, Sptr.Col]                + ")->");            // Move to the next node:            Sptr = Sptr.next;        }        Console.WriteLine("NULL");Â
        // Print the reconstructed matrix        Console.WriteLine(            "Original Matrix Re-Construction:");Â
        for (i = 0; i < R; i++) {            for (j = 0; j < C; j++) {                Console.Write(OriginalMatrix[i, j] + ", ");            }            Console.WriteLine("");        }    }Â
    // Driver Code    public static void Main()    {        // Create a head of the linked list        MatrixNode MNHead = null;        SparseNode SNHead = null;        int[, ] Matrix = new int[, ] { { 0, 1, 0, 0, 0 },                                       { 0, 1, 0, 0, 0 },                                       { 0, 0, 2, 0, 0 },                                       { 0, 3, 0, 0, 4 },                                       { 0, 0, 5, 0, 0 } };Â
        // Create a head of the linked list        MNHead            = ConstructSparseMatrix(MNHead, Matrix, SNHead);        // Sparse matrix Re-Construction        ReConstructArray(MNHead);    }}Â
// Linked list nodeclass SparseNode {Â Â Â Â public int data;Â Â Â Â public int Col;Â Â Â Â public int Row;Â Â Â Â public SparseNode next;}Â
// Store the head pointer of the linked// list and the size of the matrixclass MatrixNode {Â Â Â Â public int[] Matrix = new int[2];Â Â Â Â public SparseNode SNPTR;}Â
// This code is contributed by Tapesh (tapeshdua420) |
Javascript
  // JavaScript code for the above approach  class SparseNode  {         // linked list node  constructor(data, Col, Row) {    this.data = data; // Assign data    this.Col = Col; // Assign Column    this.Row = Row; // Assign Row    this.next = null; // Initialize next as null  }}Â
class MatrixNode {  constructor(Matrix, SNPTR) {    this.Matrix = Matrix; // Initialize matrix    this.SNPTR = null; // Initialize SNPTR as null  }}Â
const R = 5;const C = 5;Â
function ConstructMNhead(MNhead, SNhead) {  // Function to initialize the head of the linked list  MNhead = new MatrixNode([R, C], SNhead);  return MNhead;}Â
function CreateList(Row, Col, data) {  // Function to create a new node  const New = new SparseNode(data, Col, Row);  return New;}Â
function AddInList(MNhead, Row, Col, data) {Â Â let Mptr = MNhead;Â Â const New = CreateList(Row, Col, data);Â
  // Function to insert a node at the beginning of the linked list  // If the head is NULL, point it to the newly created node  if (Mptr.SNPTR === null) {    Mptr.SNPTR = New;    return MNhead;  }Â
  // Insert this node at beginning  New.next = Mptr.SNPTR;Â
  // Update the head pointer  Mptr.SNPTR = New;  return MNhead;}Â
function ConstructSparseMatrix(MNhead, Matrix) {  // Function to construct the sparse matrix using linked list  let Mptr = MNhead;Â
  // If the head pointer is NULL  if (MNhead === null) {    MNhead = ConstructMNhead(MNhead);  }  Mptr = MNhead;Â
  // Traverse the matrix, row-wise  for (let i = 0; i < Mptr.Matrix[0]; i++) {    for (let j = 0; j < Mptr.Matrix[1]; j++) {Â
      // For all non-zero values, push them in linked list      if (Matrix[i][j]) {        MNhead = AddInList(MNhead, i, j, Matrix[i][j]);      }    }  }  return MNhead;}function ReConstructArray(MNhead) {  let Sptr = MNhead.SNPTR;Â
  // Create a 2D array  const OriginalMatrix = [];Â
  // Initialize all the elements in the original matrix as 0  for (let i = 0; i < MNhead.Matrix[0]; i++) {    OriginalMatrix.push([]);    for (let j = 0; j < MNhead.Matrix[1]; j++) {      OriginalMatrix[i].push(0);    }  }Â
  // Print the linked list representation  console.log("Linked list representation:");  console.log("<br>")  // Iterate while sptr pointer is not NULL  while (Sptr !== null)  {       // Update the element in the original matrix and print the current node    OriginalMatrix[Sptr.Row][Sptr.Col] = Sptr.data;    console.log(`(${Sptr.Row}, ${Sptr.Col}, ${OriginalMatrix[Sptr.Row][Sptr.Col]})->`);Â
    // Move to the next node    Sptr = Sptr.next;  }  console.log("None");  console.log("<br>")Â
  // Print the reconstructed matrix  console.log("Original Matrix Re-Construction:");  console.log("<br>")  for (let i = 0; i < R; i++) {    for (let j = 0; j < C; j++) {      console.log(OriginalMatrix[i][j]+" ");    }   console.log("<br>")  }}// Create a 2D matrixconst Matrix =[[0, 1, 0, 0, 0],          [0, 1, 0, 0, 0],          [0, 0, 2, 0, 0],          [0, 3, 0, 0, 4],          [0, 0, 5, 0, 0]]Â
// Create a head of the linked listlet MNhead = null;Â
// Construct the sparse matrixMNhead = ConstructSparseMatrix(MNhead, Matrix);Â
// Re-construct the original matrixReConstructArray(MNhead);Â
// This code is contributed by lokeshpotta20. |
Linked list representation: (4, 2, 5)->(3, 4, 4)->(3, 1, 3)->(2, 2, 2)->(1, 1, 1)->(0, 1, 1)->NULL Original Matrix Re-Construction: 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0,
Time Complexity: O(N*M)Â
Auxiliary Space: O(N*M)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



