Google Ads

Monday, May 25, 2009

Sparse Matrix - Using Linked List

#include “stdio.h”
#include “conio.h”
struct node
{
int data;
struct node *link;
};
struct node *head=NULL,*newnode,*last;
int zero=0,v=0,i,j,m,n;
void main()
{
clrscr();
printf("\n Enter The Value of rows:");
scanf("%d",&m);
printf("\n Enter The Value of columns:");
scanf("%d",&n);
printf("\n Enter The Value For Matrix\n");
for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { newnode=(struct node*)malloc(sizeof(struct node)) scanf("%d",&newnode->data);
newnode->link=NULL;
if(head==NULL)
{
head=newnode;
last=newnode;
}
else
{
last->link=newnode;
last=newnode;
}
}
}
last=head;
while(last!=NULL)
{
if(last->data==0)
zero++;
else
v++;
last=last->link;
}
if(zero>v)
printf("\n The given matrix is sparse matrix\n");
else
printf("\n The given matrix is not a sparse matrix
last=head;
for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { printf("%d\t",last->data);
last=last->link;
}
printf("\n");
}
getch();
}



Output will be


Enter The Value of rows: 3

Enter The Value of columns: 3

Enter the Value for Matrix
0 1 0
2 0 0
0 3 1

Rows Columns Values
1 2 1
2 1 2
3 2 3
3 3 1

The given matrix is sparse matrix.

The Number Zeros Is: 5

No comments:

Post a Comment