输入两个稀疏向量,求它们的内积。要求用单链表存储稀疏向量。
时间: 2024-05-08 15:21:47 浏览: 20
可以定义一个稀疏向量的节点结构体,包含三个属性:索引值、值和指向下一节点的指针。然后用单链表将稀疏向量表示出来。对于两个稀疏向量的内积,可以遍历两个单链表,如果两个节点的索引值相同,则将它们的值相乘并加入内积的结果中。
下面是代码实现:
```c++
#include <iostream>
using namespace std;
// 稀疏向量节点结构体
struct SparseVectorNode {
int index; // 索引值
double value; // 值
SparseVectorNode* next; // 指向下一节点的指针
};
// 计算两个稀疏向量的内积
double dotProduct(SparseVectorNode* v1, SparseVectorNode* v2) {
double result = 0.0;
while (v1 != nullptr && v2 != nullptr) {
if (v1->index == v2->index) {
result += v1->value * v2->value;
v1 = v1->next;
v2 = v2->next;
} else if (v1->index < v2->index) {
v1 = v1->next;
} else {
v2 = v2->next;
}
}
return result;
}
// 创建稀疏向量
SparseVectorNode* createSparseVector(double values[], int indices[], int n) {
SparseVectorNode* head = nullptr;
for (int i = 0; i < n; i++) {
if (values[i] != 0) {
SparseVectorNode* node = new SparseVectorNode;
node->index = indices[i];
node->value = values[i];
node->next = head;
head = node;
}
}
return head;
}
int main() {
double values1[] = {1.0, 2.0, 0.0, 3.0};
int indices1[] = {0, 1, 3, 4};
SparseVectorNode* v1 = createSparseVector(values1, indices1, 4);
double values2[] = {2.0, 0.0, 4.0, 1.0};
int indices2[] = {0, 2, 3, 4};
SparseVectorNode* v2 = createSparseVector(values2, indices2, 4);
double result = dotProduct(v1, v2);
cout << "The dot product of the two sparse vectors is " << result << endl;
return 0;
}
```
输出结果为:
```
The dot product of the two sparse vectors is 7
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)