예제 #1
0

def reverse_ll_2(ll):
    return reverse(ll, None)


def reverse(node, prev_node):
    if node is None:
        # the end of the ll is reached, return the previous node
        # that'll be the first node in the reversed ll
        return prev_node

    # send node.next as current node and node as previous node in the next step
    result = reverse(node.next, node)
    # change the pointer of the current node to point to the previous node
    node.next = prev_node

    return result


###########
# Testing #
###########

# import build_ll and print_ll methods from ll_helpers.py
from ll_helpers import build_ll, print_ll

# Test 1
# Correct result => 4 -> 3 -> 2 -> 1
print_ll(reverse_ll(build_ll([1, 2, 3, 4])))
print_ll(reverse_ll_2(build_ll([1, 2, 3, 4])))
        total = transfer + v1 + v2
        transfer = total // 10

        if l1 is None:
            # if the first list is shorter than the second, add new elements at the end
            pointer.next = ListNode(None)
        pointer = pointer.next
        pointer.val = total % 10

    return start.next


###########
# Testing #
###########

# import build_ll and print_ll methods from ll_helpers.py
from ll_helpers import build_ll, print_ll

# Test 1
# Correct result => 7 -> 0 -> 8
ll1 = build_ll([2, 4, 3])
ll2 = build_ll([5, 6, 4])
print_ll(add_two_numbers(ll1, ll2))

# Test 2
# Correct result => 8 -> 9 -> 0 -> 0 -> 1
ll1 = build_ll([9, 9, 9, 9])
ll2 = build_ll([9, 9])
print_ll(add_two_numbers(ll1, ll2))
예제 #3
0
def remove_duplicates(nums):
    if nums is None:
        return nums
    pointer = nums

    while pointer.next is not None:
        if pointer.val == pointer.next.val:
            # skip the next value because it's a duplicate
            pointer.next = pointer.next.next
        else:
            # search next
            pointer = pointer.next

    return nums


###########
# Testing #
###########

# import build_ll and print_ll methods from ll_helpers.py
from ll_helpers import build_ll, print_ll

# Test 1
# Correct result => 1 -> 2
print_ll(remove_duplicates(build_ll([1, 1, 2])))

# Test 2
# Correct result => 0 -> 1 -> 2 -> 3 -> 4
print_ll(remove_duplicates(build_ll([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])))
예제 #4
0
    while head is not None:
        if i % 2 == 1:
            oddPointer.next = head
            oddPointer = oddPointer.next
        else:
            evenPointer.next = head
            evenPointer = evenPointer.next

        head = head.next
        i += 1

    evenPointer.next = None
    oddPointer.next = even.next

    return odd.next


###########
# Testing #
###########

# import build_ll and print_ll methods from ll_helpers.py
from ll_helpers import build_ll, print_ll

# Test 1
# Correct result => 1 -> 3 -> 5 -> 2 -> 4
print_ll(odd_even_ll(build_ll([1, 2, 3, 4, 5])))

# Test 2
# Correct result => 2 -> 3 -> 6 -> 7 -> 1 -> 5 -> 4
print_ll(odd_even_ll(build_ll([2, 1, 3, 5, 6, 4, 7])))