我用数组指针与连表做了一个 但我觉得这样有一点别扭,如果是二维数组不是更简单吗?? 现在我把我的代码发上给你: #include<iostream> using std::cout; using std::cin; using std::endl; #define MAX 3 typedef struct Elemment{//定义元素 int data; int line; struct Elemment *next; }Elemment; void CreatMatr(Elemment *[]);//用指针数组创建距阵 void TurnMatr(Elemment *[]);//转置 void Display(Elemment *[]);//输出 int main() { Elemment *M[MAX]; for(int i=0;i<MAX;i++) M[i]=NULL; CreatMatr(M); TurnMatr(M); Display(M); return 0; } void CreatMatr(Elemment *M[]) { int i,j; int elem; Elemment *p,*q; cout<<"input the elem of Matrix:"<<endl; for(i=0;i<MAX;i++) { for(j=0;j<MAX;j++) { cin>>elem; p=new Elemment; p->data=elem; p->line=j; p->next=NULL; if(M[i]==NULL) q=M[i]=p; else{ q->next=p; q=p; } } }
}
void TurnMatr(Elemment *M[]) { Elemment *former,*later; int temp; for(int i=0;i<MAX;i++) for(int j=i+1;j<MAX;j++)//对角线不用变化,而两三角对称交换.注意一下这里的j=i+1 { former=M[i]; while(former->line!=j) former=former->next; temp=former->data; later=M[j]; while(later->line!=i) later=later->next; former->data=later->data; later->data=temp; } } void Display(Elemment *M[]) { Elemment *q; cout<<"\n转置后的距阵:"<<endl; for(int row=0;row<MAX;row++) { q=M[row]; while(q!=NULL) { cout<<q->data<<' '; q=q->next; } cout<<endl; } }