using
System;
class
Program {
static
int
R = 5;
static
int
C = 5;
public
static
MatrixNode
ConstructMNhead(MatrixNode MNhead, SparseNode SNhead)
{
MNhead =
new
MatrixNode();
MNhead.Matrix[0] = R;
MNhead.Matrix[1] = C;
MNhead.SNPTR = SNhead;
return
MNhead;
}
public
static
SparseNode CreateList(
int
Row,
int
Col,
int
data)
{
SparseNode New =
new
SparseNode();
New.data = data;
New.Col = Col;
New.Row = Row;
return
New;
}
public
static
MatrixNode
AddInList(MatrixNode MNhead,
int
Row,
int
Col,
int
data)
{
MatrixNode Mptr = MNhead;
SparseNode New = CreateList(Row, Col, data);
if
(Mptr.SNPTR ==
null
) {
Mptr.SNPTR = New;
return
MNhead;
}
New.next = Mptr.SNPTR;
Mptr.SNPTR = New;
return
MNhead;
}
public
static
MatrixNode
ConstructSparseMatrix(MatrixNode MNhead,
int
[, ] Matrix,
SparseNode SNhead)
{
int
i, j;
MatrixNode Mptr = MNhead;
if
(MNhead ==
null
) {
MNhead = ConstructMNhead(MNhead, SNhead);
}
Mptr = MNhead;
for
(i = 0; i < Mptr.Matrix[0]; i++) {
for
(j = 0; j < Mptr.Matrix[1]; j++) {
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;
int
[, ] OriginalMatrix
=
new
int
[MNhead.Matrix[0], MNhead.Matrix[1]];
for
(i = 0; i < MNhead.Matrix[0]; i++) {
for
(j = 0; j < MNhead.Matrix[1]; j++) {
OriginalMatrix[i, j] = 0;
}
}
Console.WriteLine(
"Linked list representation:"
);
while
(Sptr !=
null
) {
OriginalMatrix[Sptr.Row, Sptr.Col] = Sptr.data;
Console.Write(
"("
+ Sptr.Row +
", "
+ Sptr.Col +
", "
+ OriginalMatrix[Sptr.Row, Sptr.Col]
+
")->"
);
Sptr = Sptr.next;
}
Console.WriteLine(
"NULL"
);
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(
""
);
}
}
public
static
void
Main()
{
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 } };
MNHead
= ConstructSparseMatrix(MNHead, Matrix, SNHead);
ReConstructArray(MNHead);
}
}
class
SparseNode {
public
int
data;
public
int
Col;
public
int
Row;
public
SparseNode next;
}
class
MatrixNode {
public
int
[] Matrix =
new
int
[2];
public
SparseNode SNPTR;
}