// C# program for Sparse Matrix Representation
// using List Of Lists
using System;
// Node to represent row - list
class row_list {
public int row_number;
public row_list link_down;
public value_list link_right;
};
// Node to represent triples
class value_list {
public int column_index;
public int value;
public value_list next;
};
class GFG {
static int R = 4;
static int C = 5;
// Function to create node for non - zero elements
static row_list create_value_node(int data, int j,
row_list z)
{
value_list temp, d;
// Create new node dynamically
temp = new value_list();
temp.column_index = j + 1;
temp.value = data;
temp.next = null;
// Connect with row list
if (z.link_right == null)
z.link_right = temp;
else {
// d points to data list node
d = z.link_right;
while (d.next != null)
d = d.next;
d.next = temp;
}
return z;
}
// Function to create row list
static row_list create_row_list(row_list start, int row,
int column,
int[, ] Sparse_Matrix)
{
// For every row, node is created
for (int i = 0; i < row; i++) {
row_list z, r;
// Create new node dynamically
z = new row_list();
z.row_number = i + 1;
z.link_down = null;
z.link_right = null;
if (i == 0)
start = z;
else {
r = start;
while (r.link_down != null)
r = r.link_down;
r.link_down = z;
}
// Firstly node for row is created,
// and then traversing is done in that row
for (int j = 0; j < 5; j++) {
if (Sparse_Matrix[i, j] != 0) {
z = create_value_node(
Sparse_Matrix[i, j], j, z);
}
}
}
return start;
}
// Function display data of LIL
static void print_LIL(row_list start)
{
row_list r;
value_list z;
r = start;
// Traversing row list
while (r != null) {
if (r.link_right != null) {
Console.WriteLine("row=" + r.row_number);
z = r.link_right;
// Traversing data list
while (z != null) {
Console.WriteLine(
"column=" + z.column_index
+ " value=" + z.value);
z = z.next;
}
}
r = r.link_down;
}
}
// Driver of the program
public static void Main(string[] args)
{
// Assume 4x5 sparse matrix
int[, ] Sparse_Matrix = { { 0, 0, 3, 0, 4 },
{ 0, 0, 5, 7, 0 },
{ 0, 0, 0, 0, 0 },
{ 0, 2, 6, 0, 0 } };
// Start with the empty List of lists
row_list start = null;
// Function creating List of Lists
start = create_row_list(start, R, C, Sparse_Matrix);
// Display data of List of lists
print_LIL(start);
}
}
// This code is contributed by phasing17.