十字链表(写的很漂亮呀!)
来源:互联网 发布:淘宝鹊桥注册 编辑:程序博客网 时间:2024/04/29 03:56
#include<stdio.h>#include<stdlib.h>#define ok 1#define error 0typedef struct node{ int i, j; int e; struct node *right, *down;}node, *linklist;typedef struct{ int mu, nu, tu; linklist *rhead, *chead;}crosslist;int init_crosslist(crosslist &M){ M.rhead = M.chead = NULL; M.nu = M.mu = M.tu = 0; return ok;}int creat_crosslist(crosslist &M){ linklist bulid, p, judge;//pointer int m, n, t, i, j, e, k, judge_number; printf("输入稀疏矩阵的行,列以及非零元素个数\n"); scanf("%d%d%d",&m, &n, &t); M.mu = m; M.nu = n; M.tu = t;// 行,和列进行初始化 M.rhead = (linklist *)malloc((m+1)*sizeof(linklist)); for(k=1; k <= m; k++){ M.rhead[k] = NULL; } M.chead = (linklist *)malloc((n+1)*sizeof(linklist)); for(k = 1; k <= n; k++){ M.chead[k] = NULL; } printf("输入非零元素行,列,非零元素\n"); for(k=0; k<t; k++){ scanf("%d%d%d",&i,&j,&e);// 判断 是否重复的输入数据,如果重复则程序结束 for(judge_number = 1; judge_number <= m; judge_number++){ judge = M.rhead[judge_number]; while(judge!=NULL){ if(judge->i == i && judge->j ==j ){ printf("此位置已经存在元素,程序将结束\n"); system("pause"); exit(0); } judge = judge->right; } }// 判断是不是超出范围 if(i>M.mu || j>M.nu){ printf("位置不合法! 无法完成操作!\n"); system("pause"); exit(0); }// 新建立的结点进行初始化 bulid=(linklist)malloc(sizeof(node)); bulid->i = i; bulid->j = j; bulid->e = e; bulid->right = NULL; bulid->down = NULL;// 完成行插入 if(M.rhead[i] == NULL || M.rhead[i]->j > j){ bulid->right = M.rhead[i]; M.rhead[i] = bulid; } else{ p = M.rhead[i]; while(p->right != NULL && p->right->j < j){ p = p->right; } bulid->right = p->right; p->right = bulid; }// 完成列插入 if(M.chead[j] == NULL || M.chead[j]->i > i){ bulid->down = M.chead[j]; M.chead[j] = bulid; } else{ p=M.chead[j]; while(p->down != NULL && p->down->i < i){ p=p->down; } bulid->down = p->down; p->down = bulid; } } return ok;}void print_list(crosslist &M){ int row_i, col_j; linklist print; printf("稀疏矩阵为\n"); for(row_i = 1; row_i <= M.mu; row_i++){ print=M.rhead[row_i]; for(col_j = 1; col_j <= M.nu; col_j++){ if(print != NULL && print->j == col_j){ printf("%d\t", print->e); print = print->right; } else{ printf("%d\t",NULL); } } printf("\n"); }}int main(){ crosslist M; char choice; while(choice!='n'&&choice!='N'){ init_crosslist(M); creat_crosslist(M); print_list(M); printf("是否要继续操作? Y/N\n"); choice = getchar(); choice = getchar(); system("cls"); } return 0;}