GeeksforGeeks App
Open App
Browser
Continue

# 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:

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