-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsparse_new.c
113 lines (102 loc) · 1.78 KB
/
sparse_new.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<stdio.h>
#include<stdlib.h>
int mat[100][100];
typedef struct node
{
int data;
int r;
int c;
struct node *next;
struct node *prev;
}node;
node *createNode(int data,int r,int c)
{
node *temp=(node *)malloc(sizeof(node));
temp->data=data;
temp->next=NULL;
temp->prev=NULL;
temp->r=r;
temp->c=c;
}
node *insertAtEnd(node *head,int data,int r,int c)
{
node *temp=createNode(data,r,c);
if(head==NULL)
{
return temp;
}
node *cur=head;
while(cur->next!=NULL)
{
cur=cur->next;
}
cur->next=temp;
temp->prev=cur;
return head;
}
node *createSparse(node *head,int m,int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(mat[i][j]!=0)
{
head=insertAtEnd(head,mat[i][j],i,j);
}
}
}
return head;
}
void getsparse(node *head,int m,int n)
{
node *cur=head;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(cur!=NULL && cur->r==i && cur->c==j)
{
printf("%d ",cur->data);
cur=cur->next;
}
else
{
printf("0 ");
}
}
printf("\n");
}
}
void traverse(node *head)
{
node *cur=head;
while(cur!=NULL)
{
printf("<--|%d||%d||%d|-->",cur->data,cur->r,cur->c);
cur=cur->next;
}
printf("\n");
}
int main()
{
int n,m;
printf("Enter number of rows and columns in a matrix\n");
scanf("%d %d",&m,&n);
printf("Enter the matrix elements\n");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
scanf("%d",&mat[i][j]);
}
}
node *head=NULL;
head=createSparse(head,m,n);
printf("Linked list:\n");
traverse(head);
printf("Sparse matrix:\n");
getsparse(head,m,n);
printf("\n");
return 0;
}