原始碼——三元組實現稀疏矩陣及其轉置
阿新 • • 發佈:2019-01-09
//三元組數值有一個特點:那就是在不同位置上的行值相同的元素 //一定是按照列值升序出現的。 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct TRIPLE//三元組成員 { int row; int col; int value; }TRIPLE; typedef struct TRIPLE_HEAD//三元組頭 { int rowCount; int colCount; int elementCount; TRIPLE *values; }TRIPLE_HEAD; TRIPLE_HEAD *initTriple(); void destoryTriple(TRIPLE_HEAD *triHd); void showTriple(TRIPLE_HEAD triHd); TRIPLE_HEAD *revange(TRIPLE_HEAD trip); TRIPLE_HEAD *revange(TRIPLE_HEAD trip) { TRIPLE_HEAD *ntrip = NULL; //new int t; //temp int *ass; //輔助陣列 int i; int index; ass = (int *)malloc(sizeof(int)* (trip.colCount + 1)); memset(ass, 0, sizeof(int) * (trip.colCount + 1));//陣列清零 for (i = 0; i < trip.elementCount; i++) { //統計列下標+1 的成員 的個數 ass[trip.values[i].col + 1]++; } printf("陣列ass元素值如下:(列 個數)\n"); for (i = 0; i < trip.colCount + 1; i++) printf("%d, %d\n", i, ass[i]); for (i = 1; i < trip.colCount; i++) ass[i] += ass[i - 1]; ntrip = (TRIPLE_HEAD *)malloc(sizeof(TRIPLE_HEAD)); *ntrip = trip; //交換行列 t = ntrip->rowCount; ntrip->rowCount = ntrip->colCount; ntrip->colCount = t; ntrip->values = (TRIPLE *)malloc(sizeof(TRIPLE)* ntrip->elementCount); for (i = 0; i < trip.elementCount; i++) { index = ass[trip.values[i].col]++; ntrip->values[index] = trip.values[i]; t = ntrip->values[index].col; ntrip->values[index].col = ntrip->values[index].row; ntrip->values[index].row = t; } free(ass); return ntrip; } void showTriple(TRIPLE_HEAD triHd) { int i, j, t = 0; printf("\n"); for (i = 0; i < triHd.rowCount; i++) { for (j = 0; j < triHd.colCount; j++) { if (t < triHd.elementCount && i == triHd.values[t].row && j == triHd.values[t].col){ printf("%d ", triHd.values[t++].value); } else{ printf("0 "); } } printf("\n"); } } void destoryTriple(TRIPLE_HEAD *triHd) { free(triHd->values); free(triHd); } TRIPLE_HEAD *initTriple() { TRIPLE_HEAD *th; int row; int col; int value; int i; th = (TRIPLE_HEAD *)malloc(sizeof(TRIPLE_HEAD)); printf("請輸入矩陣的階數(行 列):"); scanf("%d%d", &th->rowCount, &th->colCount); printf("請輸入有效元素的個數:\n"); scanf("%d", &th->elementCount); th->values = (TRIPLE *)malloc(sizeof(TRIPLE)* th->elementCount); for (i = 0; i < th->elementCount; i++) { printf("請輸入第%d個元素(行 列 值)(共%d個):", i+1, th->elementCount); scanf("%d%d%d", &row, &col, &value); th->values[i].row = row; th->values[i].col = col; th->values[i].value = value; } return th; } void main(void) { TRIPLE_HEAD *trip, *revTrip; trip = initTriple(); showTriple(*trip); revTrip = revange(*trip); showTriple(*revTrip);//轉置之後的稀疏矩陣 destoryTriple(trip); destoryTriple(revTrip); system("pause"); }