Skip to content

famo2414-art/advance-algorithms-w2-array-implementation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

advance-algorithms-w2-array-implementation

#include using namespace std;

// Node structure for Linked List struct Node { int row; int col; int value; Node* next; };

// SparseMatrix class class SparseMatrix { private: Node* head;

public: SparseMatrix() { head = nullptr; }

// Function to insert a new non-zero element
void insert(int row, int col, int value) {
    if (value == 0) return; // we don’t store zero values

    Node* newNode = new Node{row, col, value, nullptr};

    if (!head) {
        head = newNode;
    } else {
        Node* temp = head;
        while (temp->next) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}

// Function to display the sparse matrix in list form
void display() {
    Node* temp = head;
    cout << "Row\tCol\tValue\n";
    while (temp) {
        cout << temp->row << "\t" << temp->col << "\t" << temp->value << "\n";
        temp = temp->next;
    }
}

// Destructor to free memory
~SparseMatrix() {
    Node* temp;
    while (head) {
        temp = head;
        head = head->next;
        delete temp;
    }
}

};

// Example usage int main() { SparseMatrix sm;

// inserting some non-zero elements
sm.insert(0, 2, 3);
sm.insert(0, 3, 4);
sm.insert(2, 1, 5);
sm.insert(3, 2, 6);

cout << "Sparse Matrix stored as Linked List:\n";
sm.display();

return 0;

}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published