使用 Python 将两个多项式(以链表形式给出)相加的程序
假设我们有两个多项式,我们需要求这两个多项式的和。多项式需要用链表表示;多项式的项将用链表节点表示。每个链表节点将包含系数值、幂值以及指向下一个链表节点的指针。我们需要返回第三个链表,它是两个链表多项式的和。
所以,如果输入类似于
1x^1 + 1x^2 = 0 和 2x^1 + 3x^0 = 0,
那么输出将是 3x^1 + 1x^2 + 3x^0 = 0
为了解决这个问题,我们将遵循以下步骤 -
dummy := 一个新的多项式节点
node := 一个新的多项式节点
当 poly1 和 poly2 不为空时,执行以下操作
如果 poly1 的幂 > poly2 的幂,则
node 的下一个 := poly1
node := poly1
poly1 := poly1 的下一个
否则,当 poly1 的幂 < poly2 的幂时,则
node 的下一个 := poly2
node := poly2
poly2 := poly2 的下一个
否则,
coef := poly1 的系数 + poly2 的系数
如果 coef 不为零,则
poly1 := poly1 的下一个
poly2 := poly2 的下一个
node 的下一个 := poly1 或 poly2
返回 dummy 的下一个
让我们看看下面的实现,以便更好地理解 -
示例
class polynomial: def __init__(self, coeff = 0, pow = 0, nxt = None): self.coefficient = coeff self.power = pow self.next = nxt def create_poly(expression): head = None for element in expression: if head == None: head = polynomial(element[0], element[1]) else: temp = head while temp.next != None: temp = temp.next if temp.next == None: temp.next = polynomial(element[0], element[1]) return head def show_poly(head): temp = head while temp.next != None: print(str(temp.coefficient) + 'x^' + str(temp.power), end = ' + ') temp = temp.next if temp.next == None: print(str(temp.coefficient) + 'x^' + str(temp.power), end=' = 0') def solve(poly1, poly2): dummy = node = polynomial() while poly1 and poly2: if poly1.power > poly2.power: node.next = node = poly1 poly1 = poly1.next elif poly1.power < poly2.power: node.next = node = poly2 poly2 = poly2.next else: coef = poly1.coefficient + poly2.coefficient if coef: node.next = node = polynomial(coef, poly1.power) poly1 = poly1.next poly2 = poly2.next node.next = poly1 or poly2 return dummy.next poly1 = create_poly([[1,1], [1,2]]) poly2 = create_poly([[2,1], [3, 0]]) poly3 = solve(poly1, poly2) show_poly(poly3)
输入
poly1 = create_poly([[1,1], [1,2]]) poly2 = create_poly([[2,1], [3, 0]])
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
3x^1 + 1x^2 + 3x^0 = 0
广告