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

• Difficulty Level : Medium
• Last Updated : 23 Jan, 2023

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:

Below is the implementation of the above approach:

## Javascript

")  // 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("
")   // Print the reconstructed matrix  console.log("Original Matrix Re-Construction:");  console.log("
")  for (let i = 0; i < R; i++) {    for (let j = 0; j < C; j++) {      console.log(OriginalMatrix[i][j]+" ");    }   console.log("
")  }}// 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.

Output

(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)

My Personal Notes arrow_drop_up