- #1
zorro
- 1,384
- 0
Homework Statement
The idea is to create following type of structure:
first_row_with_a_nonzero_cell->next_row_with_a_nonzerocell->...->NULL
rowN_with_a_nonzerocell->firstnonzerocolinrowN->nextnonzerocolinrowN...->NULL
Input file is a 20x50 sparse matrix.
The only problem I have is while switching to next row, when a '\0' is encountered.
The new rownode I create using link2 function, should point to the header of the cell node of same row. But I created head1 as a pointer to the first non zero element of the first row. And I can't use the same head1 to point to the first non zero element of the second row.
How do I make sure that everytime a new row is created, the rownode of that row points to the first non zero cell of the same row?
Homework Equations
The Attempt at a Solution
Code:
#include <stdio.h>
struct cellnode {
int val;
int col;
struct cellnode *nextcell;
};
struct rownode {
int row;
struct rownode *firstcell;
struct rownode *nextrow;
};
struct rownode * create_rownode(){
struct rownode *new;
new = (struct rownode *)malloc(sizeof(struct cellnode));
return new;
};struct rownode *head2=NULL;
struct cellnode * create_cellnode(){
struct cellnode *new;
new = (struct cellnode *)malloc(sizeof(struct cellnode));
return new;
};struct cellnode *head1=NULL;
void link1(int v,int c){
struct cellnode *temp,*new;
new=create_cellnode();
new->val=v;
new->col=c;
if(head1==NULL)
head1=new;
else{
temp=head1;
while(temp->nextcell!=NULL){
temp=temp->nextcell;
}
temp->nextcell=new;
}
if(c=19)
new->nextcell=NULL;
}
void link2(int r){
struct rownode *temp,*new;
new=create_rownode();
new->row=r;
new->firstcell=head1;
new->nextrow=NULL;
if(head2==NULL)
head2=new;
else{
temp=head2;
while(temp->nextrow!=NULL){
temp=temp->nextrow;
}
temp->nextrow=new;
}
}
main() {
FILE *fp;
char i,c;
int n,col=0,row=0;
fp=fopen("1.txt","r");
if(fp==NULL){
printf("cannot open");
return;
}
else printf("File Opened\n");
while(((i=getc(fp))!=EOF)){
printf("%c",i);
}
rewind(fp);
while(((i=getc(fp))!=EOF)){
while(i!='\0'){
fscanf(fp,"%d%c",&n,&c);
if(n!=0){
link1(n,col);
}
i=getc(fp);
col++;
}
if(i='\0'){
link2(row);
head1=NULL;
col=0;
row++;
}
}
}