C++ use linked list to sum two sparse matrix

Note 1: The programs should read the matrices from the *.txt files, NOT from keyboard. Use the sample codes provided on Stream. Use either the C or the C++ style.
txt file is
4 4

0 1 0 0

0 0 2 0

0 3 0 4

0 0 0 5

Note 2: Make sure that values of zero are not nodes in the linked list (after all, that's the point in implementing the sparse matrix code!).

Note 3: The output must be in this format. This example has 4x4 matrices:

Matrix 1: 1 2 3 4 5

0 1 0 0

0 0 2 0

0 3 0 4

0 0 0 5

Matrix 2: 1 1 2 3 4 10 3 3

1 1 2 0

0 0 3 0

0 4 0 10

0 0 3 3

Matrix Result: 1 2 2 5 7 14 3 8

1 2 2 0

0 0 5 0

0 7 0 14

0 0 3 8

If the matrix is all zeros, it should be printed like this, indicating that the corresponding linkedĀ­list is empty:

Matrix 2:

0 0 0 0

0 0 0 0

0 0 0 0

0 0 0 0

Anyone can help me ? I can not write the addMatrix function.

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
//You need to add your own AddNode and PrintLL functions, as well as an AddMatrices function
//

#include <stdio.h>
#include <stdlib.h>
struct Node {  //declaration
    int row;
    int column;
    int value;
    Node *next;
};
Node *A, *B;  //declaration


void read_matrix(Node* &a, char *file_name){
    //reads a matrix from a file

    int col = 0, row = 0, value = 0;  
    FILE *input = NULL;
    input = fopen(file_name, "r");

    if(input == NULL){
        printf("Cannot open file %s. Exiting.\n", file_name);
        exit(0);
    }
    //reads the matrix dimensions from the first line 
    fscanf(input, "%d %d", &row, &col); 

    //read matrix 
    for(int i = 0; i < row; ++i){
        for(int j = 0; j < col; ++j){
        //reads each value from this row (second line onwards)
            fscanf(input, "%d", &value);
            if(value == 0) continue;
        //
            //Include your own add_node(a, i, j, value); function here
        //
        //The next line is for debbuging, it can be commented later
        printf("Element at (%d %d) is different than zero and it is: %d ",i,j,value);
        }
    //the next line is for debbuging purposes, it can be commented out later
    printf("\n");
    }

    fclose(input);
}

int main() {
    A = NULL;  // ALL linked-lists start empty
    read_matrix(A, (char*)"matrix1.txt");
}
Last edited on
These are one way mapping right?

How can you reconstruct the matrix from the serialsed output?
Matrix 1: 1 2 3 4 5

0 1 0 0

0 0 2 0

0 3 0 4

0 0 0 5 
Your linked list should have an imposed sort order on it (sorting on the row, column).

To "add" your sparse matrices, you should merge them, much like a merge sort, except when two keys compare equal (the elements have the same row, column), combine them into a single value in the resulting linked list by adding their values together.

Hope this helps.
Topic archived. No new replies allowed.