就做了创建,加法还有输出,减法与加法类似``
- #include<iostream>
- #include<malloc.h>
- using namespace std;
- #define OK 1
- #define ERROR 0
- #define OVERFLOW -2
- typedef int Status;
- typedef struct OLNode{
- int i,j;
- int e;
- struct OLNode *right,*down;
- }OLNode,*OLink;
- typedef struct{
- OLink *rhead,*chead;
- int mu,nu,tu;
- }CrossList;
- Status CreateSMatrix_OL(CrossList &M){
- cin>>M.mu>>M.nu>>M.tu;
- M.rhead=(OLink*)malloc((M.mu+1)*sizeof(OLink));
- M.chead=(OLink*)malloc((M.nu+1)*sizeof(OLink));
- if(!M.rhead||!M.chead) return ERROR;
- int k=1,i,j,e;
- OLink p,q;
- for(;k<=M.mu;k++)
- M.rhead[k]=NULL;
- for(k=1;k<=M.nu;k++)
- M.chead[k]=NULL;
- k=0;
- while(k<M.tu)
- {
- cin>>i>>j>>e;
- p=(OLink)malloc(sizeof(OLNode));
- if (!p) return ERROR;
- p->i=i;p->j=j;p->e=e; p->down=NULL; p->right=NULL;
- if(M.rhead[i]==NULL||M.rhead[i]->j>j){
- p->right=M.rhead[i];
- M.rhead[i]=p;}
- else {
- for(q=M.rhead[i];(q->right)&&(q->right->j<j);q=q->right);
- p->right=q->right;q->right=p;}
- if(M.chead[j]==NULL||M.chead[j]->i>i){
- p->down=M.chead[j];
- M.chead[j]=p;}
- else {
- for(q=M.chead[j];(q->down)&&q->down->i<i;q=q->down);
- p->down=q->down;q->down=p;}
- k++; }
- return OK; }
- Status AddSMatrix_OL(CrossList &A,CrossList &B){
- if(!(A.mu==B.mu&&A.nu==B.nu)) return ERROR;
- OLink pa,pb,pre,pp;
- for(int row=1;row<=A.mu;row++)
- for(pre=NULL,pa=A.rhead[row],pb=B.rhead[row];pb;)
- {
- if(pa==NULL||pa->j>pb->j){
- if(!pre)
- {A.rhead[row]=pb;pb->right=pa;pa=pb;}
- else
- {pre->right=pb; pb->right=pa;}
- if(!A.chead[pb->j]||A.chead[pb->j]->i>pb->i) { pb->down=A.chead[pb->j];A.chead[pb->j]=pb;}
- else {
- for(pp=A.chead[pb->j];(pp->down)&&(pp->down->i<pb->i);pp=pp->down);
- pb->down=pp->down;pp->down=pb;}
- if(!pa){ pre=pa;pa=pa->right;}
- pb=pb->right; }
- else if(pa->j < pb->j) {pre=pa;pa=pa->right;}
- else {
- int sum=pa->e+pb->e;
- if(sum) {pa->e=sum;pre=pa;}
- else {
- pre->right=pa->right;
- for(pp=A.chead[pa->j];pp->down&&(pp->down->i)<pa->j;pp=pp->down);
- pp->down=pa->down;
- }
- pa=pa->right;
- pb=pb->right; }
- }
- return OK;
- }
- void Print(CrossList A)
- {
- int col;
- for(int row=1;row<=A.mu;row++)
- {
- col=1;
- for(OLink pa=A.rhead[row];pa;pa=pa->right)
- { while(col<pa->j)
- {
- cout<<"0"<<" ";
- col++; }
- cout<<pa->e<<" ";col++;}
- while(col<=A.nu)
- {
- cout<<"0"<<" ";
- col++;}
- cout<<endl;
- }
- }
- int main()
- {
- CrossList A,B;
- CreateSMatrix_OL(A);
- Print(A);
- CreateSMatrix_OL(B);
- Print(B);
- AddSMatrix_OL(A,B);
- Print(A);
- return 0;}