在论稀疏矩阵

来源:互联网 发布:建筑 大数据 编辑:程序博客网 时间:2024/05/17 08:45

 /* 在论稀疏矩阵 */
#include "stdio.h"
struct clist
{
 int row;
 int col;
 int data;
 struct clist *right;
 struct clist *down;
};
typedef struct clist cnode;
typedef cnode *clink;
/*创建稀疏数组的头结点数组*/
clink creatematrix(int row,int col)
{
 clink head;
 int len,i;
 /*计算数组长度,取列和行最大值*/
 if(row>col)
 len=row;
 else
 len=col;
 /*分配头结点数组数组内存*/
 head=(clink)malloc(sizeof(cnode));
 if(!head) return NULL;
 head[0].row=row;/*数组的行*/
 head[0].col=col;/*数组的列*/
 
 for(i=0;i<len;i++)/*用循环设置指针初值*/
 {
  head[i].right=&head[i];
  head[i].down=&head[i];
 }
 return head;
}
/*稀疏数组的数组元素插入*/
clink insertmatrix(clink head,int row,int col,int value)
{
 clink new_node;
 clink pos;
 /*创建新结点分配结点内存*/
 new_node=(clink)malloc(sizeof(cnode));
 if(!new_node) return NULL;
 /*稀疏数组的实际大小*/
 new_node->row=row;
 new_node->col=col;
 new_node->data=value;
 /*插入由指针down接成列链表*/
 pos=&head[col];
 /*用循环来插入行row*/
 while(pos->down!=&head[col]&&row>pos->down->row)
 pos=pos->down;
 new_node->down=pos->down;
 pos->down=new_node;
 /*插入由指针right接成行链表*/
 pos=&head[row];
 /*用循环来插入列col*/
 while(pos->right!=&head[row]&&col>pos->right->col)
 pos=pos->right;
 pos->right=new_node;
 return head;
}
/*稀疏数组的输出*/
void printmatrix(clink head)
{
 clink ptr,now;
    int i;
    printf("行   列   值/n");
    printf("==============/n");
    /*从down指针串成的链表来输出*/
    for(i=0;i<head[0].col;i++)
    {
     now=head[i].down;
     ptr=&head[i];
     while(now!=ptr)
     {
      printf("[%3d][%3d]=[%4d]/n",now->row,now->col,now->data);
      /*输出结点数据*/
      now=now->down;
     }
    }
}
void main()
{
    clink head;
    int sparse[5][6]={
                   0,0,1,0,0,0,
                   0,3,0,9,0,0,
                   0,4,0,0,0,2,
                   7,0,0,0,3,0,
                   0,0,0,6,0,0,};
    int i,j;
    head=creatematrix(5,6);
    for(i=0;i<5;i++)
    for(j=0;j<6;j++)
    if(sparse[i][j]!=0)
    /*稀疏数组元素插入*/
    head=insertmatrix(head,i,j,sparse[i][j]);
    printmatrix(head);
}