/*******************************************************************/ matrix_plus(matnode_type *hm1,matnode_type *hm2) { int c; matnode_type *q; matnode_type *p1,*p2; matnode_type *h1,*h2; matnode_type *pre1,*pre2; h1=hm1->content.next; h2=hm2->content.next; pre1=h1;p1=h1->right; pre2=h2;p2=h2->right; if(!hm1||!hm2||hm1->row!=hm2->row||hm1->col!=hm2->col)/*hm1或hm2为空or行数或列数不相等*/ { printf("error:at least one matrix don't exist!\n"); printf("or:\nrow or column doesn't fit.\n"); return; } while(h1->row==0&&h2->row==0)/*没有回到总表头*/ { while(p1->col!=0||p2->col!=0) { if(p1->col<p2->col&&p1->col!=0||p2->col==0) { pre1->right=p1->right;/*把p1从hm1移除*/ p1->right=p2;pre2->right=p1;/*把p1插入hm2中*/ c=p1->col;/*用c标记p1的列号*/ q=cp[c]; while(q->down!=cp[c]&&q->down->row<p1->row) { q=q->down; } p1->down=q->down;q->down=p1;/*完成插入*/ p1=pre1->right; } else if(p1->col==p2->col) { pre1->right=p1->right;/*从h1中删除p1节点*/ p2->content.value+=p1->content.value; free(p1); p1=pre1->right; pre2=p2;p2=p2->right; } else { pre2=p2;p2=p2->right; } } /*转到下一行*/ h1=h1->content.next;h2=h2->content.next; p1=h1->right;p2=h2->right; pre1=h1;pre2=h2; } } /******************************************************************/ out_matnod_list(matnode_type *hm) { int m,n,up,down,i,j; matnode_type *p,*h; m=hm->row;n=hm->col;/*存储该矩阵的行列值*/ for(i=0,h=hm->content.next;i<m;h=h->content.next,i++)/*输出m行*/ { down=1; for(p=h->right;p!=h;p=p->right) { up=p->col; for(j=down;j<up;j++)/*充0*/ printf("0 "); printf("%d ",p->content.value); down=up+1; } for(j=down;j<=n;j++) printf("0 "); printf("\n"); }
} /******************************************************************/ main() { printf("please input the first matrix:\n"); hm1=crt_matnod_list(hm1);/*建立{dy}个矩阵*/ if(hm1)out_matnod_list(hm1);/*输出{dy}个矩阵*/ printf("please input the second matrix:\n"); hm2=crt_matnod_list(hm2);/*建立第二个矩阵*/ if(hm2)out_matnod_list(hm2);/*输出第二个矩阵*/ matrix_plus(hm1,hm2);/*矩阵相加*/ printf("the result of the sum is as follows:\n"); if(hm2)out_matnod_list(hm2);/*输出矩阵相加后的结果*/ del_matnod_list(hm1);/*删除{dy}个矩阵*/ printf("delete hm1 sucessful...\n"); del_matnod_list(hm2);/*删除第二个矩阵*/ printf("delete hm2 sucessful...\n"); getch(); }
|