I’m coding the program that using linked list to store a sparse matrix. First I create a class “Node” contains the index of entry, value of entry and two pointers to next row and next column. Second I find on Google that I need to create the class Matrix like this code below but I don’t understand the meaning of Node **rowList and node** columnList. Why they use a pointer to a pointer there and how could I implement a matrix from that? Thank you so much.
class Node
{
public:
int iValue, jValue;
float value;
Node *rowPtr;
Node *colPtr;
};
class Matrix
{
Node **rowList; // rowList is the pointer to the array of rows
Node **columnList; // columnList is the pointer to the array of columns
int rows, cols; // number of rows and columns
}
It appears to be exactly what the comment says. They are arrays. Presumably
rowListwill be an array ofrowselements, andcolumnListwill be an array ofcolselements. The reason it’s aNode**is that each item in the array is aNode*. A pointer to an array always has an extra level of indirection (an extra*). That means when you index a single element out of that array you get a value of typeNode*again.The arrays are created like this:
When you need to delete them (in the destructor for
Matrix):As for your question on how to implement your matrix from that, that’s really up to you. Presumably when you create a node at position
(i, j), you append that node to each ofrowListandcolumnList. ie:But it’s not that simple, because the node obviously must be linked into both a row and column list. At the very basic level, and using the structures you’ve provided, here’s one way:
Now using the above with my original example:
For ordered insert
Since you have code already, I will offer my take on it. But you still need to do some work yourself.
Let’s just clean things up to begin with. It’s a class, and you’re using C++ so please use your C++ knowledge:
So, now you need to implement the
Matrix::inputDatafunction… Essentially you do what your friend was trying to do, but without the errors and memory leaks. That means you start like this:Now, you finish the function off, and don’t forget to do the column indexing…