def reverse_linked_list_recursion(head: Node) -> Node:
    """ Solution - Recursion
    Time Complexity - O(N) - iterate through the linked list.
    Space Complexity - O(N) - since we are using recursion, so it will 
    call recursion stack.

    For better understanding with slides:
    https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/
    """

    # Recursion stop condition, the current node is None or
    # the next node is None. For example, for linked list 
    # 1 -> 2 -> 3 -> None, it will stop at node 3 and return it.
    if head == None or head.next == None:
        return head
    
    # Temp will be the last node, in this case, 3.
    temp = reverse_linked_list_recursion(head.next)
    # Assume all nodes after the current node's next node are all 
    # reversed, now we need to reverse the next node and the 
    # current node.For example, when 3 is returned, temp will be 3, 
    # while head will be 2, and 2.next.next is now assigned to 2 
    # which means 3.next = 2, so the node is reversed.
    head.next.next = head
    # To avoid a list loop, we need to set head.next to None, in 
    # this case, 2.next is set to None for now.
    head.next = None

    # Return the last node or the first node in the reversed list.
    # Here it's 3.
    return temp
Esempio n. 2
0
def reverse_sum(x, y, carry):
    """Recurively sum the linked list by node value with carry."""
    if x is None and y is None and carry == 0:
        return None
    value = carry
    value += x.value if x else 0
    value += y.value if y else 0
    carry, value = divmod(value, 10)
    node = Node(value)
    next_x = x.next if x else None
    next_y = y.next if y else None
    node.next = reverse_sum(next_x, next_y, carry)
    return node
Esempio n. 3
0
def is_palindrome_reverse(head):
    """Iteratively check if is palindrome by comparing to reversed."""
    prev = None
    current = head
    counter = 0
    while current:
        counter += 1
        node = Node(current.value)
        node.next = prev
        prev = node
        current = current.next

    for _ in range(counter // 2):
        if head.value != prev.value:
            return False
        head = head.next
        prev = prev.next
    return True
def is_palindrome_reverse(head):
    """Iteratively check if is palindrome by comparing to reversed."""
    prev = None
    current = head
    counter = 0
    while current:
        counter += 1
        node = Node(current.value)
        node.next = prev
        prev = node
        current = current.next

    for _ in range(counter // 2):
        if head.value != prev.value:
            return False
        head = head.next
        prev = prev.next
    return True