显示来自链表的稀疏矩阵,该链表仅存储了非零元素
Displaying a Sparse matrix from a linked list which has stored only non zeros element
我有一个用户输入的稀疏矩阵和一个链表,它只存储非零元素并忽略所有零。现在,我的目标是从这个链表中,尝试从稀疏矩阵中获取所有元素,包括零和非零元素并显示它。有人请给我看一条光路或一些说明或想法
稀疏矩阵,用户输入所有元素(零和非零)
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]。但是,这可能会导致不希望的结果,因为矩阵运算通常需要非常具体的维度,并且信息丢失可能会给您带来不好的结果。希望这有帮助!
- 反向给定链表中的K节点
- 为什么C中的通用链表中存储的数据已损坏
- 将从格式化文本文件读取的文本数据存储到链表
- C++将存储在链表中的两个大数字相乘
- 相同的地址存储在链表的头部
- 如何将自己的链表实现从存储整数更改为存储个人数据
- 显示来自链表的稀疏矩阵,该链表仅存储了非零元素
- 存储类对象的C++模板链表-未处理的异常访问冲突读取位置
- 使用c++通过文件存储和检索链表
- 为什么链表使用指针而不是将节点存储在节点内部
- 在双链表中,指针不是存储彼此的地址,而是指向相同的位置
- 打印存储在链表中的数据时出现问题
- C++ 将链表存储在链表中
- 将地址和布尔值存储在一个单词中,以实现无锁双链表
- 从文件中读取,存储到链表中,然后再次打印到文件中
- 如何使用链表来存储表,并在表中搜索项
- 为什么这个自定义链表不存储 c++ 中给出的每个元素?
- 将值存储在链表中的结构中
- malloc和heap:用于存储大小和链表信息的额外内存
- 将数据存储到链表中