#include <stdio.h>
#include <stdlib.h>
#define maxsize 100
typedef struct
{
int i, j;
char v;
} str;
typedef struct
{
str *data;
int row, col, count; //矩阵的行数,列数,和非零元素个数
} Array;
int row, col, n;
Array *Create_array()
{
Array *p;
int i, j;
p = (Array *)malloc(sizeof(Array));
printf("请输入矩阵的行列:\n");
scanf("%d%d", &row, &col);
printf("请输入非零元素的个数:\n");
scanf("%d", &n);
i = 0;
p->data = (str *)malloc(n * sizeof(str));
do
{
scanf("%d %d %c", &((p->data + i)->i), &((p->data + i)->j), &((p->data + i)->v));
i++;
} while (i < n);
p->row = row;
p->col = col;
p->count = n;
return p;
}
Array *Convert_array(Array *A, Array *B)
{
int count[A->col];
int pos[A->col];
B=(Array *)malloc(sizeof(Array));
B->data=(str *)malloc(n * sizeof(str));
B->row = A->col;
B->col = A->row;
B->count = n;
if (A->count > 0)
{
for (int i = 0; i < A->col; i++)
count[i] = 0;
for (int i = 0; i < A->count; i++)
count[(A->data + i)->j]++;
}
pos[0] = 0;
for (int col = 1; col < A->col; col++)
pos[col] = pos[col - 1] + count[col - 1];
for(int i=0;i<A->count;i++)
{
int k =pos[(A->data+i)->j];
(B->data+k)->i=(A->data+i)->j;
(B->data+k)->j=(A->data+i)->i;
(B->data+k)->v=(A->data+i)->v;
pos[(A->data+i)->j]++;
}
return B;
}
void print_array(Array *p)
{
int j;
j = p->count;
for (int i = 0; i < j; i++)
printf("%d %d %c\n", (p->data + i)->i, (p->data + i)->j, (p->data + i)->v);
}
int main()
{
Array *L,*L1;
L = Create_array();
print_array(L);
L1=Convert_array(L,L1);
print_array(L1);
return 0;
}
没有用
{
str data[maxsize];
}
纯粹为了考验我的指针。
之所以用列。
就是保证在转换后是行优先,
所以转换前 按列排序好。
这个思路是找B.data(0到 count)中恰当的位置。