编写一个算法程序实现把2个稀疏矩阵分别存储在2个顺序三元组中 急用!!!!!!!!!!!!!!

C语言
2024-11-22 21:02:30
推荐回答(1个)
回答(1):

此程序我做了测试没问题
编译软件(virtual c++ 6.0)望你能学习进步
#include
#include
#include
#define MaxRows 100
#define MaxColumns 100
typedef int ElemType;
struct CrossNode
{
int row,col;
ElemType val;
CrossNode *down,*right;
};
struct CLMatrix
{
int m,n,t;
CrossNode *rv[MaxRows+1];
CrossNode *cv[MaxColumns+1];
};
void InitMatrix(CLMatrix &M)
{
M.m=0;M.n=0;M.t=0;
for(int i=1;i<=MaxRows;i++)
M.rv[i]=NULL;
for(i=1;i<=MaxColumns;i++)
M.cv[i]=NULL;
}
void InputMatrix(CLMatrix &M,int m,int n);
void OutputMatrix(CLMatrix &M,int m,int n);
void Transpose(CLMatrix &M,int m,int n);
void main()
{
CLMatrix Q,P,N;
InitMatrix(Q);
InitMatrix(P);
InitMatrix(N);
cout<<"请您输入矩阵的行数与列数:";
int m,n;
cin>>m>>n;
cout<<"请以三元组的形式进行输入:"< InputMatrix(Q,m,n);
cout<<"您输入的稀疏矩阵为:"< OutputMatrix(Q,m,n);
cout<<"转置后的稀疏矩阵为:"< Transpose(Q,m,n);
}
void InputMatrix(CLMatrix &M,int m,int n)
{
M.m=m;M.n=n;
int row,col,val;
int k=0;
cin>>row>>col>>val;
while(row!=0)
{
k++;
CrossNode *cp,*newptr;
newptr=new CrossNode;
newptr->row=row;
newptr->col=col;
newptr->val=val;
newptr->down=newptr->right=NULL;
cp=M.rv[row];
if(cp==NULL)
M.rv[row]=newptr;
else
{
while(cp->right!=NULL)
cp=cp->right;
cp->right=newptr;
}
cp=M.cv[col];
if(cp==NULL)
M.cv[col]=newptr;
else
{
while(cp->down!=NULL)
cp=cp->down;
cp->down=newptr;
}
cin>>row>>col>>val;
}
M.t=k;
}
void Transpose(CLMatrix &M,int m,int n)
{
CLMatrix S;
InitMatrix(S);
S.m=M.m;S.n=M.n;
for(int i=1;i<=S.m;i++)
{
for(int j=1;j<=S.n;j++)
{
int val=0;
CrossNode *cp,*newptr;
newptr=new CrossNode;
newptr->row=i;
newptr->col=j;
newptr->val=val;
newptr->down=newptr->right=NULL;
cp=S.rv[i];
if(cp==NULL)
S.rv[i]=newptr;
else
{
while(cp->right!=NULL)
cp=cp->right;
cp->right=newptr;
}
cp=S.cv[j];
if(cp==NULL)
S.cv[j]=newptr;
else
{
while(cp->down!=NULL)
cp=cp->down;
cp->down=newptr;
}
}
}
for(i=1;i<=M.m;i++)
{
CrossNode *sp1=S.rv[i];
CrossNode *mp1=M.rv[i];
while(mp1!=NULL)
{
while(sp1->colcol)
sp1=sp1->right;
sp1->val=mp1->val;
mp1=mp1->right;
}
}
for(int x=1;x<=S.m;x++)
{
while(S.cv[x]!=NULL)
{
cout<val;
S.cv[x]=S.cv[x]->down;
}
cout< }

}
void OutputMatrix(CLMatrix &M,int m,int n)
{
CLMatrix S;
InitMatrix(S);
S.m=M.m;S.n=M.n;
for(int i=1;i<=S.m;i++)
{
for(int j=1;j<=S.n;j++)
{
int val=0;
CrossNode *cp,*newptr;
newptr=new CrossNode;
newptr->row=i;
newptr->col=j;
newptr->val=val;
newptr->down=newptr->right=NULL;
cp=S.rv[i];
if(cp==NULL)
S.rv[i]=newptr;
else
{
while(cp->right!=NULL)
cp=cp->right;
cp->right=newptr;
}
cp=S.cv[j];
if(cp==NULL)
S.cv[j]=newptr;
else
{
while(cp->down!=NULL)
cp=cp->down;
cp->down=newptr;
}
}
}
for(i=1;i<=M.m;i++)
{
CrossNode *sp1=S.rv[i];
CrossNode *mp1=M.rv[i];
while(mp1!=NULL)
{
while(sp1->colcol)
sp1=sp1->right;
sp1->val=mp1->val;
mp1=mp1->right;
}
}
for(int x=1;x<=S.m;x++)
{
while(S.rv[x]!=NULL)
{
cout<val;
S.rv[x]=S.rv[x]->right;
}
cout< }
}