def reverse_and_compare(node): original_head = node # Reverse linked list reversed_head = None while node: new_node = Node(node.val) new_node.next = reversed_head reversed_head = new_node node = node.next # Compare while original_head or reversed_head: if original_head.val != reversed_head.val: return False original_head = original_head.next reversed_head = reversed_head.next return reversed_head is None and original_head is None
def backward_solution(first, second, carry=0): if first is None and second is None and carry == 0: return None result = Node(None) value = carry if first is not None: value += first.val if second is not None: value += second.val # Last digit of number result.val = value % 10 if first is not None or second is not None: next_node = backward_solution(first and first.next, second and second.next, 1 if value >= 10 else 0) result.next = next_node return result
def _get_kth_node(node, kth): while kth > 0 and node: node = node.next kth -= 1 return node def insert_after(head, value, node): while head: if head.val == value: head.next = node head = head.next if __name__ == "__main__": first = create_list([0, 1, 2, 3, 4, 5, 6, 7]) second = create_list([11, 12, 13, 14]) intersecting_node = Node(-1) intersecting_node.next = Node(-2) intersecting_node.next.next = Node(-3) insert_after(first, 7, intersecting_node) insert_after(second, 14, intersecting_node) print(f"Solution({first}, {second}) -> ", brute_force_solution(first, second)) print(f"Solution({first}, {second}) -> ", count_and_compare_solution(first, second))