# 三元组顺序表-转置运算-三种算法

166人阅读 评论(0)
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000

typedef int ElementType;

typedef struct {
int row;
int col;
ElementType value;
}Tripe;

void TSMatrixInit();
void Print();
//按列序递增进行转置
void TransposeTSMatrix1();
void TransposeTSMatrix2();
void TransposeTSMatrix3();

typedef struct {
Tripe data[MAXSIZE+1];
int rows;
int cols;
int nums;
}TSMatrix;

void main () {
TSMatrix *s = NULL;
TSMatrix *t = NULL;
s = (TSMatrix *)malloc(sizeof(TSMatrix));
t = (TSMatrix *)malloc(sizeof(TSMatrix));
TSMatrixInit(s);
printf("输出s :\n");
Print(s);
// TransposeTSMatrix1(s,t);
// TransposeTSMatrix2(s,t);
// TransposeTSMatrix3(s,t);
printf("输出B :\n");
Print(t);
}

void TSMatrixInit(TSMatrix *s) {
int i;
int Rmax = 0;
int Cmax = 0;
printf("请设置元素个数:");
scanf("%d",&s->nums);
printf("row col value\n");
for (i = 1; i <= s->nums; i++) {
scanf("%d %d %d",&s->data[i].row,&s->data[i].col,&s->data[i].value);
if (Rmax < s->data[i].row) {
s->rows = s->data[i].row;
}
else {
s->rows = Rmax;
}
if (Cmax < s->data[i].col) {
s->cols = s->data[i].col;
}
else {
s->cols = Cmax;
}
}
}

void Print(TSMatrix *s) {
int i;
printf("元素个数 : %d\n",s->nums);
printf("最大列数 : %d\n",s->rows);
printf("最大行数 : %d\n",s->cols);
printf("row col value\n");
for (i = 1; i <= s->nums; i++) {
printf("%d %d %d\n",s->data[i].row,s->data[i].col,s->data[i].value);
}
}
//时间复杂度O(a->cols * a->nums)
void TransposeTSMatrix1(TSMatrix *a, TSMatrix *b) {
int i, j, k;
b->rows = a->cols;
b->cols = a->rows;
b->nums = a->nums;
if (b->nums > 0) {
j = 1;
for (k = 1; k <= a->cols; k++) {
for (i = 1; i <= a->nums; i++) {
if (a->data[i].col == k) {
b->data[j].row = a->data[i].col;
b->data[j].col = a->data[i].row;
b->data[j].value = a->data[i].value;
j++;
}
}
}
}
}

void TransposeTSMatrix2 (TSMatrix *a, TSMatrix *b) {
int i, j, k;
b->rows = a->cols;
b->cols = a->rows;
b->nums = a->nums;
if (b->nums > 0) {
j = 1;
for (k = 1; k <= a->cols; k++) {
for (i = 1; i <= a->nums; i++) {
if (a->data[i].col == k) {
b->data[j].row = a->data[i].col;
b->data[j].col = a->data[i].row;
b->data[j].value = a->data[i].value;
j++;
}
}
if (j > a->nums) {
break;
}
}
}
}

void TransposeTSMatrix3(TSMatrix *a, TSMatrix *b) {
int i, j ,min;
b->rows = a->cols;
b->cols = a->rows;
b->nums = a->nums;
i = 1;
while (i <= a->nums) {
min = 1;
for (j = 1; j <= a->nums; j++) {
if (a->data[j].col < a->data[min].col) {
min = j;
}
}
b->data[i].row = a->data[min].col;
b->data[i].col = a->data[min].row;
b->data[i].value = a->data[min].value;
i++;
a->data[min].col = a->cols + 1;
}
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1255次
• 积分：106
• 等级：
• 排名：千里之外
• 原创：9篇
• 转载：0篇
• 译文：1篇
• 评论：0条
评论排行