Python用双链表一元一次方程相加
时间: 2023-11-05 15:14:12 浏览: 129
一元多项式相加,用两个链表组织两个一元多项式,将相加的结果保存在前一个链表中。
5星 · 资源好评率100%
以下是Python代码,实现双链表一元一次方程相加:
```python
class Node:
def __init__(self, coefficient, power):
self.coefficient = coefficient
self.power = power
self.next = None
self.prev = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_node(self, coefficient, power):
new_node = Node(coefficient, power)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
current = self.head
while current is not None and current.power > power:
current = current.next
if current is None:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
elif current.power == power:
current.coefficient += coefficient
elif current.prev is None:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
else:
new_node.next = current
new_node.prev = current.prev
current.prev.next = new_node
current.prev = new_node
def __str__(self):
current = self.head
result = ''
while current is not None:
result += '{}x^{} + '.format(current.coefficient, current.power)
current = current.next
return result[:-3]
def add_equations(eq1, eq2):
result = LinkedList()
node1 = eq1.head
node2 = eq2.head
while node1 is not None and node2 is not None:
if node1.power > node2.power:
result.add_node(node1.coefficient, node1.power)
node1 = node1.next
elif node1.power < node2.power:
result.add_node(node2.coefficient, node2.power)
node2 = node2.next
else:
result.add_node(node1.coefficient + node2.coefficient, node1.power)
node1 = node1.next
node2 = node2.next
while node1 is not None:
result.add_node(node1.coefficient, node1.power)
node1 = node1.next
while node2 is not None:
result.add_node(node2.coefficient, node2.power)
node2 = node2.next
return result
eq1 = LinkedList()
eq1.add_node(3, 2)
eq1.add_node(2, 1)
eq1.add_node(1, 0)
print(eq1)
eq2 = LinkedList()
eq2.add_node(4, 3)
eq2.add_node(1, 1)
eq2.add_node(2, 0)
print(eq2)
eq3 = add_equations(eq1, eq2)
print(eq3)
```
上述代码定义了一个`Node`类和一个`LinkedList`类,`Node`类表示一个双链表节点,包含系数和指数两个属性,以及指向前一个节点和后一个节点的指针;`LinkedList`类表示一个双链表,包含头节点和尾节点两个属性,以及添加节点和打印链表的方法。`add_node`方法实现了按指数从高到低的顺序添加节点的功能,如果指数相同则合并同类项。
`add_equations`方法接受两个一元一次方程的链表作为参数,遍历这两个链表,并对相同指数的节点进行系数相加的操作,最后返回一个新的链表。
在代码的最后,我们创建了两个链表`eq1`和`eq2`,分别表示$3x^2+2x+1$和$4x^3+x^1+2$两个一元一次方程,然后将它们相加,并打印出相加后的链表`eq3`,表示$4x^3+3x^2+3x+3$的一元一次方程。
阅读全文