if node_list[i] != node_list[j]: return False i += 1 j -= 1 return True def is_palindrome(self, head: ListNode) -> bool: ''' 返回交点 Args: head: 节点head Returns: 布尔值 ''' node_list = [] if not head: return True while head: node_list.append(head.val) head = head.next return self.is_palindrome_list(node_list) if __name__ == '__main__': arr = [1, 2, 3, 3, 2, 1] list_node = ListNode() head = list_node.create_list_node_array(arr) solution = Solution() result = solution.is_palindrome(head) print(result)
return self.add_two_number_helper(l1, l2, 0) def add_two_number_helper(self, l1: ListNode, l2: ListNode, v: 0) -> ListNode: ''' 相加帮助类 Args: l1: l1链表 l2: l2链表 v: 值 Returns: 链表 ''' if not l1 and not l2: return None if v == 0 else ListNode(v) if l1: v += l1.val l1 = l1.next if l2: v += l2.val l2 = l2.val return ListNode(v % 10, self.add_two_number_helper(l1, l2, v / 10)) if __name__ == '__main__': l1 = ListNode.create_list_node_array([1, 2, 3]) l2 = ListNode.create_list_node_array([2, 3, 4]) solution = Solution() result = solution.add_two_number(l1, l2) print(result)
def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode: ''' 合并两个链表 Args: l1: l1链表 l2: l2链表 Returns: 合并后的链表 ''' if not l1: return l2 if not l2: return l1 if l1.val <= l2.val: l1.next = self.merge_two_lists_2(l1.next, l2) return l1 else: l2.next = self.merge_two_lists_2(l1, l2.next) return l2 if __name__ == '__main__': list_node = ListNode() l1 = list_node.create_list_node_array([1, 2, 4]) l2 = list_node.create_list_node_array([1, 3, 4, 5]) solution = Solution() result = solution.merge_two_lists_2(l1, l2) print(result.val) assert result.val == 1
class Solution: def get_intersection_node(self, head_a: ListNode, head_b: ListNode) -> ListNode: ''' 返回交点 Args: head_a: 链表a head_b: 链表b Returns: 交点 ''' if not head_a or not head_b: return None p_A = head_a p_B = head_b while p_A != p_B: p_A = head_b if not p_A else p_A.next p_B = head_a if not p_B else p_B.next return p_A if __name__ == '__main__': arr1 = [4, 1, 8, 4, 5] l1 = ListNode.create_list_node_array(arr1) arr2 = [5, 0, 1, 8, 4, 5] l2 = ListNode.create_list_node_array(arr2) solution = Solution() result = solution.get_intersection_node(l1, l2) print(result) assert result == None