带行指针向量的单链表存储稀疏矩阵

C语言 码拜 9年前 (2015-10-19) 2137次浏览
#include <stdio.h>

#include <malloc.h>

typedef int DataType;
struct LNode//数据结构

{

int col;//列

DataType value;//元素值

struct LNode *next;//指向同行下一个非零结点指针

};
void Create(struct LNode*row[]);

void InArray(struct LNode *row[],int r,int col,int value);

void PrintArray(struct LNode *row[]);
int main(int argc, char* argv[])

{

struct LNode* row[5]={ NULL };

Create(row);

InArray(row,0,0,11);

InArray(row,0,3,14);

InArray(row,0,4,15);

InArray(row,1,1,22);

InArray(row,2,4,35);

InArray(row,4,0,51);

InArray(row,4,2,53);
PrintArray(row);

return 0;

}
void Create(struct LNode*row[])

{

struct LNode* p;

int i;

for(i=0;i<5;i++)

{

p=(struct LNode *)malloc(sizeof(struct LNode));

p->col=1;

p->value=0;

p->next=NULL;

row[i]->next=p;//Debug在这就死了,应该是和指针指向非法地址有关

}

}
//插入函数

void InArray(struct LNode *row[],int r,int col,int value)

{

struct LNode *q,*s;
s=(struct LNode *)malloc(sizeof(struct LNode *));

s->col=col;

s->value=value;

s->next=NULL;
if(row[r]->next==NULL)

row[r]->next=s;

q=row[r]->next;

while(q!=NULL)

q=q->next;
s->next=q->next;

q->next=s;
}
void PrintArray(struct LNode *row[])

{

int i,j,value;

for(i=0;i<5;i++)

for(j=0;j<5;j++)

{

if(row[i]->col==j)

{

value=row[i]->value;

row[i]=row[i]->next;

}

else value=0;

printf(”    %d”,value);

}

printf(“\n”);

}

解决方案:40分
#include <stdio.h>
#include <malloc.h>
typedef int DataType;
struct LNode//数据结构
{
    int col;//列
    DataType value;//元素值
    struct LNode *next;//指向同行下一个非零结点指针
};
void InArray(struct LNode *row[],int r,int col,int value);
void PrintArray(struct LNode *row[]);
int main() {
    struct LNode *row[5]= {NULL};
    InArray(row,0,0,11);
    InArray(row,0,3,14);
    InArray(row,0,4,15);
    InArray(row,1,1,22);
    InArray(row,2,4,35);
    InArray(row,4,0,51);
    InArray(row,4,2,53);
    PrintArray(row);
    return 0;//程序退出时,malloc的内存会被操作系统自动回收,所以不用free
}
void InArray(struct LNode *row[],int r,int col,int value) {
    struct LNode *q,*s;
    s=(struct LNode *)malloc(sizeof(struct LNode));
    s->col=col;
    s->value=value;
    s->next=NULL;
    if (row[r]==NULL) {
        row[r]=s;
        return;
    } else {
        q=row[r];
        while (q->next!=NULL) q=q->next;
        q->next=s;
    }
}
void PrintArray(struct LNode *row[]) {
    int i,j,value;
    struct LNode *q;
    for(i=0;i<5;i++) {
        for(j=0;j<5;j++) {
            q=row[i];
            value=0;
            while (1) {
                if (q==NULL) break;
                if (q->col==j) {
                    value=q->value;
                    break;
                } else {
                    q=q->next;
                }
            }
            printf("%4d",value);
        }
        printf("\n");
    }
}
//  11   0   0  14  15
//   0  22   0   0   0
//   0   0   0   0  35
//   0   0   0   0   0
//  51   0  53   0   0
//

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明带行指针向量的单链表存储稀疏矩阵
喜欢 (0)
[1034331897@qq.com]
分享 (0)