コード例 #1
0
def removeNode(node: Node) -> bool:
    if node is None or node.next is None:
        return False

    nextNode: Node = node.next
    node.data = nextNode.data
    node.data = nextNode.next
    return True
コード例 #2
0
def delete_middle_node(n: Node) -> None:
    """
  Imagine: a -> b -> c -> d -> e, and we're given c, told to remove it.
  Idea: if we wanted to remove c cleanly, we would be given access to b. But we aren't.
  To work around this fact, we copy d's value <- c, then b -> d -> d -> e, then we just have to 
  remove the second d. 

  Super weird problem. But also just two lines of Python. Ha!
  """
    n.data = n.next.data
    n.next = n.next.next
    return None
コード例 #3
0
ファイル: ctci_llist.py プロジェクト: vvkdby/Python-Practice
def addSameSize(head1, head2, carry):
    #check if the lists are empty
    if head1 is None:
        return None

    result = Node()

    result.next = addSameSize(head1.next, head2.next, carry)

    sum = head1.data + head2.data + carry
    carry = sum / 10
    sum = sum % 10

    result.data = sum

    return result
コード例 #4
0
def addRec(num1, num2, carry):
    if (not num1 and not num2 and carry == 0):
        return None

    result = Node(0)
    value = carry
    if (num1):
        value += num1.data
    if (num2):
        value += num2.data

    result.data = value % 10

    if (num1 or num2):
        result.next = addRec(num1.next if num1 else None,
                             num2.next if num2 else None,
                             1 if value >= 10 else 0)
    print(result.data)
コード例 #5
0
def deleteMiddleNode(node: ll.Node):

    #grab data of next node in the list
    #head -> targetnode -> (node2) -> tail
    nextNode = node.next

    #set data of current node to next node
    #head -> (targetnode.data = node2.data) -> node2 -> tail
    node.data = nextNode.data

    #set current node next to node after next
    #head -> targetnode -> tail
    #(node2) -> tail
    nextNextNode = nextNode.next

    if (nextNextNode is None):
        node.next = None
    else:
        node.next = nextNextNode
コード例 #6
0
ファイル: AddTwoNumbers.py プロジェクト: jfseo/PySolutions
def add_two_list_recursive(list_1,list_2,carry=0):
    if not list_1 and not list_2:
        if carry > 0:
            return Node(carry)
        return None
    else:
        value = carry
        result_node = Node()
        if list_1:
            value += list_1.data
        if list_2:
            value += list_2.data
        if value >= 10:
            carry = 1
        else:
            carry = 0
        result_node.data = value % 10
        next_node = add_two_list_recursive(list_1.next,list_2.next,carry)
        result_node.next = next_node
        return result_node