#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;
}
Comments
Leave a comment