By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,807 Members | 1,492 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,807 IT Pros & Developers. It's quick & easy.

read sparse matrix with liked list

P: 17
hello every body
code below is about reading sparse matrix.
Anyone understand this code?
Expand|Select|Wrap|Line Numbers
  1. istream& operator>>(istream& is, Matrix& matrix)
  2. { Triple s; int p; is >> s.row >> s.col >> s.value;
  3. if (s.row > s.col) p = s.row; else p = s.col;
  4. matrix.headnode = new MatrixNode(FALSE, &s);
  5. if (p==0) {matrix.headnode->right = matrix.headnode; return is;}
  6. MatrixNodePtr *head = new MatrixNodePtr[p];
  7. for (int i = 0; i < p; i++) head[i] = new MatrixNode(TRUE, 0);
  8. int CurrentRow = 0; MatrixNode *last = head[0];
  9. for (i = 0; i < s.value; i++)
  10. { Triple t; is >> t.row >> t.col >> t.value;
  11. if (t.row > CurrentRow) {
  12. last->right = head[CurrentRow];
  13. CurrentRow = t.row;
  14. last = head[CurrentRow]; }
  15. last = last->right = new MatrixNode(FALSE, &t);
  16. head[t.col]->next = head[t.col]->next->down = last;
  17. }
  18. last->right = head[CurrentRow];
  19. for (i = 0; i < s.col; i++) head[i]->next->down = head[i];
  20. for (i = 0; i < p-1 ; i++) head[i]->next = head[i+1];
  21. head[p-1]->next = matrix.headnode;
  22. matrix.headnode->right = head[0];
  23. delete [] head;
  24. return is;
  25. }
  26.  
And these are the classes that use:
Expand|Select|Wrap|Line Numbers
  1. struct Triple{int value,row,clo;}
  2. class Matrix;
  3. class MatrixNode{
  4.     friend class Matrix;
  5.     friend istream& operator>>(istream&,Matrix&);
  6.     MatrixNode *down,*right;
  7.     bool head; //a head node or not
  8.     union{ //anonymous union
  9.         MatrixNode *next;
  10.         Triple triple;
  11.     };
  12. public:
  13.     MatrixNode(bool b,Triple *t): head(b){//ctor
  14.         if(b){ right=down=next=this;}
  15.         else triple =*t;
  16.     }
  17. };
  18. typedef MatrixNode *MatrixNodePtr;
  19. class Matrix{
  20.     friend istream& operator>>(istream&,Matrix&);
  21.     MatrixNode *headnode;
  22. public:
  23.     ~Marix();//dtor
  24. };
  25.  
Best Regard,
Nov 28 '10 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.