Leetcode 1774 Solution
This article provides solution to leetcode question 1774 (add-two-polynomials-represented-as-linked-lists)
Access this page by simply typing in "lcs 1774" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/add-two-polynomials-represented-as-linked-lists
Solution
# Definition for polynomial singly-linked list.
# class PolyNode:
# def __init__(self, x=0, y=0, next=None):
# self.coefficient = x
# self.power = y
# self.next = next
class Solution:
def addPoly(self, poly1: 'PolyNode', poly2: 'PolyNode') -> 'PolyNode':
dummy_head = PolyNode()
prev_node = dummy_head
node1 = poly1
node2 = poly2
while node1 or node2:
power1 = node1.power if node1 else -1
power2 = node2.power if node2 else -1
v = 0
power = 0
if power1 == power2:
v = node1.coefficient + node2.coefficient
power = power1
node1 = node1.next
node2 = node2.next
elif power1 > power2:
v = node1.coefficient
power = power1
node1 = node1.next
elif power1 < power2:
v = node2.coefficient
power = power2
node2 = node2.next
if v != 0:
prev_node.next = PolyNode(v, power)
prev_node = prev_node.next
return dummy_head.next