正常实现矩阵的变换我们都是通过将矩阵通过二维数组的方式存储,在输出端控制好输出的内容来实现矩阵的相应变换,并不会改变数组的存放。但当题目要求使用链表而不是数组方式存储时,题目就会变难很多。
但本文提出一种思想将链表标上数组的序号即可讲问题简单化
在构建结构体时多设两个整型变量x,y来标号
typedef struct LNode{
int x;
int y;
int data;
struct LNode *next;
}LNode, *LinkList;
并在输出时完成如下操作,即可讲链表表示成数组的形式
void init(LinkList &L,int m,int n)
{
L=(LinkList)malloc(sizeof(LNode));
LinkList current,prev;
prev=L;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
current=(LinkList)malloc(sizeof(LNode));
cin>>current->data;
current->x=i;
current->y=j;
prev->next=current;
prev=current;
}
}
current->next=NULL;
}
例如此时p->x,p->y已经相当于数组a[x][y]的x,y标号。
源代码如下:
1.用链表表示矩阵并实现矩阵的转置。
#include"iostream"
#include "cmath"
using namespace std;
//数组:
/*
int main()
{
cout<<"please input the two dimensiomns of the matrix:"<<endl;
int m,n;
cin>>m>>n;
cout<<"please input the elements of the matrix:"<<endl;
int a[10][10];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<"The original matrix you inputed is:"<<endl;
for(i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"The transposed matrix is:"<<endl;
for(i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cout<<a[j][i]<<" ";
}
cout<<endl;
}
return 0;
}
*/
//链表
typedef struct LNode{
int x;
int y;
int data;
struct LNode *next;
}LNode, *LinkList;
void init(LinkList &L,int m,int n)
{
L=(LinkList)malloc(sizeof(LNode));
LinkList current,prev;
prev=L;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
current=(LinkList)malloc(sizeof(LNode));
cin>>current->