显示来自链表的稀疏矩阵,该链表仅存储了非零元素

Displaying a Sparse matrix from a linked list which has stored only non zeros element

本文关键字:链表 存储 元素 显示      更新时间:2023-10-16

我有一个用户输入的稀疏矩阵和一个链表,它只存储非零元素并忽略所有零。现在,我的目标是从这个链表中,尝试从稀疏矩阵中获取所有元素,包括零和非零元素并显示它。有人请给我看一条光路或一些说明或想法

稀疏矩阵,用户输入所有元素(零和非零)

int row;
int column;
int count=0;
int sparseMatrix[10][10];
cout<<"Enter Number of Rows: ";
cin>>row;
cout<<endl;
cout<<"Enter Number of Column: ";
cin>>column;
cout<<endl;
int i,j;
cout<<"Enter Elements in the Matrix: ";
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
cin>> sparseMatrix[i][j];
if (sparseMatrix[i][j]==0)
count++;
}
}

链接列表,仅从稀疏矩阵中读取非零元素并显示它们

void PrintList(struct node* start)
{
struct node *temp, *r, *s;
temp = r = s = start;
cout<<"row_position:";
while(temp != NULL)
{
cout<<temp->rowposition;
temp = temp->next;
}
cout<<endl;
printf("column_postion: ");
while(r != NULL)
{
cout<<r->columnposition;
r = r->next;
}
cout<<endl;
printf("Value: ");
while(s != NULL)
{
cout<<s->value;
s = s->next;
}
cout<<endl;
}

创建链接列表节点

struct node {
int value;
int rowposition;
int columnposition;
struct node *next;
};
void createNewNode (struct node** start, int NonZeroElement, int rowIndex, int columnIndex) // functions with parameter
{
struct node *temp, *r;
temp = *start;
if (temp==NULL)
{
temp=(struct node *) malloc (sizeof (struct node)); // creates a new node dynamically
temp -> value= NonZeroElement;
temp -> rowposition = rowIndex;
temp -> columnposition = columnIndex;
temp -> next=NULL;
*start = temp;
}
else
{
while (temp->next != NULL)
temp = temp->next;
// Create new node dynamically
r = (struct node *) malloc (sizeof(struct node));
r->value = NonZeroElement;
r->rowposition = rowIndex;
r->columnposition = columnIndex;
r->next = NULL;
temp->next = r;
}
}

我的目标是显示此矩阵,如下图所示: 这就是矩阵的显示方式。我的目标 这是我到目前为止在图片中的输出:

到目前为止,我此代码的当前输出图片

我认为您需要考虑函数调用 PrintList 的结构或稀疏矩阵数据结构本身。在数据结构或 printList 方法中的某个地方应该是稀疏矩阵所需的逐列结构。考虑一个 4x4 矩阵的问题,除了 [1,2] 处的一个值外,所有零。打印方法根本不知道您想要 4x4 矩阵,除了 [1,2] 处的单个值,除非打印方法收到行数和列数的输入,或者数据结构本身保留这些值。这应该允许函数调用更加自我支持,而不是依赖主体中的代码来为您指示。 另一方面,由于您无论如何都必须打印行 x 列值,因此为行和列创建嵌套的 for 循环并检查当前链表节点行和列值是否确实是嵌套循环结构的控制变量中的值,因此开销很小。如果没有,你可以打印零,当你到达内部for循环的末尾时,你可以打印一个新行来处理你的代码。 当然,你可以只有一个值的链表,你可以用它来设置矩阵的维数。在我给出的示例中,您最终会打印出 2 x 3 矩阵,而不是所需的 4 x 4,因为最大行和列值为 [1,2]。但是,这可能会导致不希望的结果,因为矩阵运算通常需要非常具体的维度,并且信息丢失可能会给您带来不好的结果。希望这有帮助!