不一样——非零元节点没了指示位置的I、j,实际上,对于确定非零元在矩阵中的位置,I、j不是必须的,看着围棋盘你就会很清楚。但是很不幸,不是把他们存起来就万事大吉了,最起码,必须考虑加法和乘法的效率,请你想想如果用上面的那种结构,如何完成。
如果你细想想,就会发现,非零元节点如果没有指示位置的域,那么做加法和乘法时,为了确定节点的位置,每次都要遍历行和列的链表。因此,为了运算效率,这个域是必须的。为了看出十字链表和单链表的差异,我从单链表派生出十字链表,这需要先定义一种新的结构,如下: class MatNode { public: int data; int row, col; union { Node<MatNode> *down; List<MatNode> *downrow; }; };
另外,由于这样的十字链表是由多条单链表拼起来的,为了访问每条单链表的保护成员,要声明十字链表类为单链表类的友元。即在class List的声明中添加friend class Matrix;
稀疏矩阵的定义和实现
#ifndef Matrix_H #define Matrix_H #include "List.h" class MatNode { public: int data; int row, col; union { Node<MatNode> *down; List<MatNode> *downrow; }; MatNode(int value = 0, Node<MatNode> *p = NULL, int i = 0, int j = 0) : data(value), down(p), row(i), col(j) {} friend ostream & operator << (ostream & strm, MatNode &mtn) { strm << ''('' << mtn.row << '','' << mtn.col << '')'' << mtn.data; return strm; } }; class Matrix : List<MatNode> { public: Matrix() : row(0), col(0), num(0) {} Matrix(int row, int col, int num) : row(row), col(col), num(num) {} ~Matrix() { MakeEmpty(); } void MakeEmpty() { List<MatNode> *q; while (first->data.downrow != NULL) { q = first->data.downrow; first->data.downrow = q->first->data.downrow; delete q; } List<MatNode>::MakeEmpty(); row = col = num = 0; } void Input() { if (!row) { cout << "输入矩阵行数:"; cin >> row; } if (!col) { cout << "输入矩阵列数:"; cin >> col; } if (!num) { cout << "输入非零个数:"; cin >> num; } if (!row || !col || !num) return; cout << endl << "请按顺序输入各个非零元素,以列序为主,输入0表示本列结束" << endl; int i, j, k, v;//i行数 j列数 k个非零元 v非零值 Node<MatNode> *p = first, *t; List<MatNode> *q; for (j = 1; j <= col; j++) LastInsert(MatNode(0, NULL, 0, j)); for (i = 1; i <= row; i++) { q = new List<MatNode>; q->first->data.row = i; p->data.downrow = q; p = q->first; } j = 1; q = first->data.downrow; First(); t = pNext(); for (k = 0; k < num; k++) { if (j > col) break; cout << endl << "输入第" << j << "列非零元素" << endl; cout << "行数:"; cin >> i; if (i < 1 || i > row) { j++; k--; q = first->data.downrow; t = pNext(); continue; } cout << "非零元素值"; cin >> v; if (!v) { k--; continue; } MatNode matnode(v, NULL, i, j); p = new Node<MatNode>(matnode); t->data.down = p; t = p; while (q->first->data.row != i) q = q->first->data.downrow; q->LastInsert(t); } } void Print() { List<MatNode> *q = first->data.downrow; cout << endl; while (q != NULL) { cout << *q; q = q->first-> |