已知稀疏矩阵A和B,编程代码实现基于三元组顺序表实现A+B的运算
时间: 2024-02-22 12:55:05 浏览: 12
以下是基于三元组顺序表实现A+B的Python代码:
```python
class TripleNode:
def __init__(self, row, col, val):
self.row = row
self.col = col
self.val = val
self.next = None
class SparseMatrix:
def __init__(self, row, col):
self.row = row
self.col = col
self.head = TripleNode(None, None, None)
def insert(self, row, col, val):
if row > self.row or col > self.col:
print("Invalid insert operation.")
return
cur = self.head
pre = None
while cur and cur.row < row:
pre = cur
cur = cur.next
while cur and cur.row == row and cur.col < col:
pre = cur
cur = cur.next
if cur and cur.row == row and cur.col == col:
cur.val += val
if cur.val == 0:
pre.next = cur.next
else:
new_node = TripleNode(row, col, val)
new_node.next = cur
if pre:
pre.next = new_node
else:
self.head = new_node
def add(self, other):
if self.row != other.row or self.col != other.col:
print("Invalid add operation.")
return
res = SparseMatrix(self.row, self.col)
cur_a = self.head.next
cur_b = other.head.next
while cur_a and cur_b:
if cur_a.row < cur_b.row or (cur_a.row == cur_b.row and cur_a.col < cur_b.col):
res.insert(cur_a.row, cur_a.col, cur_a.val)
cur_a = cur_a.next
elif cur_a.row > cur_b.row or (cur_a.row == cur_b.row and cur_a.col > cur_b.col):
res.insert(cur_b.row, cur_b.col, cur_b.val)
cur_b = cur_b.next
else:
res.insert(cur_a.row, cur_a.col, cur_a.val + cur_b.val)
cur_a = cur_a.next
cur_b = cur_b.next
while cur_a:
res.insert(cur_a.row, cur_a.col, cur_a.val)
cur_a = cur_a.next
while cur_b:
res.insert(cur_b.row, cur_b.col, cur_b.val)
cur_b = cur_b.next
return res
```
示例:
```python
# 创建稀疏矩阵A
A = SparseMatrix(3, 3)
A.insert(0, 0, 1)
A.insert(0, 2, 2)
A.insert(1, 1, 3)
A.insert(2, 0, 4)
A.insert(2, 2, 5)
# 创建稀疏矩阵B
B = SparseMatrix(3, 3)
B.insert(0, 1, 6)
B.insert(1, 0, 7)
B.insert(1, 1, 8)
B.insert(2, 2, 9)
# 计算A+B
C = A.add(B)
# 输出结果
cur = C.head.next
while cur:
print(cur.row, cur.col, cur.val)
cur = cur.next
```
输出结果为:
```
0 0 1
0 1 6
0 2 2
1 0 7
1 1 11
2 0 4
2 2 14
```