Esempio n. 1
0
def sll_swap_node(sll: Singlellist, x, y) -> None:
    if x == y:
        return
    # S1: find prev_x, curr_x
    ptr = sll.head
    while ptr.next.value != x:
        ptr = ptr.next
    prev_x = ptr
    curr_x = ptr.next

    # S1: find prev_y, curr_y
    ptr = sll.head
    while ptr.next.value != y:
        ptr = ptr.next
    prev_y = ptr
    curr_y = ptr.next

    # S2: change prev
    if prev_x is None:  # x is the head
        sll.head = curr_y
    else:
        prev_x.next = curr_y

    if prev_y is None:  # y is the head
        sll.head = curr_x
    else:
        prev_y.next = curr_x

    # S3: change next
    temp = curr_x.next
    curr_x.next = curr_y.next
    curr_y.next = temp
Esempio n. 2
0
def concatenating_linked_lists(
    l1: Singlellist,
    l2: Singlellist,
) -> Singlellist:
    result = Singlellist()
    result.head = l1.head
    l1.tail.next = l2.head
    return result
Esempio n. 3
0
def reverse_sll_loop(sll: Singlellist) -> Singlellist:
    if len(sll) == 1:
        return sll
    head = sll.head
    prev_node = None
    curr_node = sll.head
    while curr_node is not None:
        next_node = curr_node.next
        curr_node.next = prev_node
        prev_node = curr_node
        curr_node = next_node

    sll.head = sll.tail
    sll.tail = head