Answer to Question #241207 in C++ for Myname

Question #241207
Write a program to convert a sparse matrix from a 2D array into
A. An array representation of nx3 size, where n is the number of non-zero elements in the
sparse matrix and each element is represented by row, column, and data.
B. A chain list (Linked list representation of the sparse matrix where each non-zero element
is represented by a node containing the data, row, column, and a pointer)
1
Expert's answer
2021-09-24T00:03:46-0400
#include <iostream>
using namespace std;
class Node{
    public:
    int data, row, col;
    Node *next;
    Node();
    Node(int, int, int);
};
Node::Node(){
    next = NULL;
}
Node::Node(int data, int row, int col){
    this->data = data;
    this->row = row;
    this->col = col;
    next = NULL;
}
class ChainList{
    static Node *head;
    int size;


    public:
    ChainList();
    void append(int, int, int);
    int len();
    void show();
};
Node* ChainList::head = NULL;
ChainList::ChainList(){
    size = 0;
}
void ChainList::append(int data, int row, int col){
    if(head == NULL){
        head = new Node(data, row, col);
        size++;
        return;
    }
    Node *curr = head;
    while(curr->next != NULL){
        curr = curr->next;
    }
    curr->next = new Node(data, row, col);
    size++;
}
int ChainList::len(){
    return size;
}
void ChainList::show(){
    Node* curr = head;
    cout<<"Row position\n";
    while(curr != NULL){
        cout<<curr->row<<" ";
        curr = curr->next;
    }
    curr = head;
    cout<<"\nColumn position\n";
    while(curr != NULL){
        cout<<curr->col<<" ";
        curr = curr->next;
    }
    curr = head;
    cout<<"\nData\n";
    while(curr != NULL){
        cout<<curr->data<<" ";
        curr = curr->next;
    }
    cout<<endl;
}
int main(){
    ChainList list;
    int size = 0, sparseMatrix[4][5] = {{0, 0, 3, 0, 4},
                                {0, 0, 5, 7, 0},
                                {0, 0, 0, 0, 0},
                                {0, 2, 6, 0, 0}};
    for(int i = 0; i < 4; i++)
    for(int j = 0; j < 5; j++){
        if(sparseMatrix[i][j] != 0){
            list.append(sparseMatrix[i][j], i, j);
            size++;
        }
    }



    int (*array)[3] = new int[size][3];


    for(int i = 0, k = 0; i < 4; i++)
    for(int j = 0; j < 5; j++){
        if(sparseMatrix[i][j] != 0){
            array[k][0] = i;
            array[k][1] = j;
            array[k][2] = sparseMatrix[i][j];
            k++;
        }
    }
    cout<<"\nChain List\n";
    list.show();
    cout<<"\nArray\n";
    for(int i = 0; i < size; i++){
        cout<<array[i][0]<<" "<<array[i][1]<<" "<<array[i][2]<<endl;
    }


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS