def remove_nth_frm_end(head, n):
    """
    2 pointer algo
    :type head: ListNode
    :type n: int
    :rtype: ListNode
    """
    tmp = Node(-1)
    tmp.next = head

    pointer_1 = tmp
    pointer_2 = tmp

    # Move over n nodes including dummy
    for i in range(n):
        pointer_2 = pointer_2.next  # set pointer_2 to n-1 th

    # Increment ptrs till you reach end of list
    while pointer_2.next:
        pointer_1 = pointer_1.next
        pointer_2 = pointer_2.next
    # Now pointer_1.next points to the nth node from the end
    pointer_1.next = pointer_1.next.next

    return head
Beispiel #2
0
def add_two_numbers(l1, l2, carry=0):
    """
    :type l1: Node
    :type l2: Node
    :rtype: Node
    """
    val = l1.val + l2.val + carry
    carry = val // 10

    final_ll = Node(val % 10)

    if (l1.next != None or l2.next != None or carry != 0):
        if l1.next == None:
            l1.next = Node(0)
        if l2.next == None:
            l2.next = Node(0)
        final_ll.next = add_two_numbers(l1.next, l2.next, carry)

    return final_ll
Beispiel #3
0
    final_ll = Node(val % 10)

    if (l1.next != None or l2.next != None or carry != 0):
        if l1.next == None:
            l1.next = Node(0)
        if l2.next == None:
            l2.next = Node(0)
        final_ll.next = add_two_numbers(l1.next, l2.next, carry)

    return final_ll


l1 = Node(2)
node2 = Node(4)
node3 = Node(3)

l1.next = node2
node2.next = node3

l2 = Node(5)
node2 = Node(6)
node3 = Node(4)

l2.next = node2
node2.next = node3

fl = add_two_numbers(l1, l2)

print(traverse_list(fl))
    next = None

    # until we have gone through to the end of the list
    while current:
        # Make sure to copy the current nodes next node to a variable next
        # Before overwriting as the previous node for reversal
        next = current.next

        # Reverse the pointer of the next
        current.next = previous

        # Go one forward in the list
        previous = current
        current = next

    return previous


# Create a list of 4 nodes
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)

# Set up order a,b,c,d with values 1,2,3,4
a.next = b
b.next = c
c.next = d

reverse(a)
print(traverse_list(a))