已知稀疏矩阵A和B,编程代码实现基于三元组顺序表实现A+B的运算
时间: 2024-02-01 11:15:59 浏览: 23
以下是基于三元组顺序表的稀疏矩阵加法代码实现:
```python
class Node:
def __init__(self, row, col, val):
self.row = row
self.col = col
self.val = val
class TriSparseMatrix:
def __init__(self, row, col, node_list):
self.row = row
self.col = col
self.node_list = node_list
def add(self, other):
if self.row != other.row or self.col != other.col:
print("Error: Matrices are not of same size!")
return None
i = j = 0
res_node_list = []
while i < len(self.node_list) and j < len(other.node_list):
if self.node_list[i].row == other.node_list[j].row:
if self.node_list[i].col == other.node_list[j].col:
res_node_list.append(Node(self.node_list[i].row, self.node_list[i].col, self.node_list[i].val + other.node_list[j].val))
i += 1
j += 1
elif self.node_list[i].col < other.node_list[j].col:
res_node_list.append(self.node_list[i])
i += 1
else:
res_node_list.append(other.node_list[j])
j += 1
elif self.node_list[i].row < other.node_list[j].row:
res_node_list.append(self.node_list[i])
i += 1
else:
res_node_list.append(other.node_list[j])
j += 1
while i < len(self.node_list):
res_node_list.append(self.node_list[i])
i += 1
while j < len(other.node_list):
res_node_list.append(other.node_list[j])
j += 1
return TriSparseMatrix(self.row, self.col, res_node_list)
```
其中,`Node`是三元组的节点类,`TriSparseMatrix`是基于三元组顺序表的稀疏矩阵类。在`add`方法中,我们对两个稀疏矩阵进行遍历,根据三元组的行列信息进行比较,并将两个矩阵对应位置的值加起来存入结果矩阵中。如果行列信息不匹配,则将行列小的节点先存入结果矩阵中。最后返回结果矩阵。