A matrix m x n that has relatively few non-zero entries is called sparse matrix. It may be represented in much less than m n space. An mxn matrix with k non-zero entries is sparse if k<<m <n. It may be faster to represent the matrix compactly as a list of the non-zero indexes and associated entries. WAP to represent a sparse matrix using linked list.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
typedef struct List
{
int date;
struct List* pNext;
}List;
void pushList(List** hd, const int d)
{
if ((*hd) == NULL)
{
(*hd) = (List*)malloc(sizeof(List));
(*hd)->pNext = NULL;
(*hd)->date = d;
}
else
{
List* p = (*hd);
while (p->pNext)
{
p = p->pNext;
}
List* nw = (List*)malloc(sizeof(List));
nw->pNext = NULL;
nw->date = d;
p->pNext = nw;
}
}
void PrintList(List* h,int col)
{
List* p = h;
int ind = 0;
while (p)
{
printf("%i ", p->date);
ind++;
p = p->pNext;
}
//print zero
for (int i = 0; i < col - ind; i++)
printf("%i ", 0);
printf("\n");
}
void clearList(List** h)
{
List* pr = NULL;
while ((*h)->pNext)
{
pr = (*h);
(*h) = (*h)->pNext;
free(pr);
}
free((*h));
}
int main()
{
int m;
int n;
printf("Enter m,n:\n");
scanf("%i%i", &m, &n);
List** ls = (List*)malloc(sizeof(List*)*m);
for (int i = 0; i < m; i++)
ls[i] = NULL;
printf("Enter elements:\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
int x;
scanf("%i", &x);
if (x != 0)
pushList(&ls[i], x);
}
}
printf("====================Output WAP List=====================\n");
for (int i = 0; i < m; i++)
PrintList(ls[i], n);
for (int i = 0; i < m; i++)
if(ls[i])
clearList(&ls[i]);
free(ls);
return 0;
}
Comments
Leave a comment