示例#1
0
def reverse_list(head: ListNode) -> ListNode:
    if not head or not head.next:
        return head
    last = reverse_list(head.next)
    head.next.next = head
    head.next = None
    return last
示例#2
0
def ls():
    lns = {x: ListNode(x) for x in range(1, 5)}
    lns[1].next = lns[2]
    lns[2].next = lns[3]
    lns[3].next = lns[4]

    return lns[1]
示例#3
0
def ans():
    lns = {x: ListNode(x) for x in range(1, 6)}
    lns[1].next = lns[4]
    lns[4].next = lns[3]
    lns[3].next = lns[2]
    lns[2].next = lns[5]

    return lns[1]
示例#4
0
def swap_pairs(head: ListNode) -> ListNode:
    if not head or not head.next:
        return head
    dummy = ListNode()
    pre, cur, nxt = None, head, head.next
    dummy.next = nxt
    while cur and nxt:
        if pre:
            pre.next = nxt
        cur.next, nxt.next = nxt.next, cur

        if cur.next:
            pre, cur, nxt = cur, cur.next, cur.next.next
        else:
            break

    return dummy.next
示例#5
0
    def reverse_n(head: ListNode, n: int) -> ListNode:
        if n == 1:
            successor[0] = head.next
            return head
        last = reverse_n(head.next, n - 1)

        head.next.next = head
        head.next = successor[0]
        return last
示例#6
0
def ls():
    lns = {x: ListNode(x) for x in range(1, 7)}
    lns[1].next = lns[2]
    lns[2].next = lns[3]

    lns[4].next = lns[5]
    lns[5].next = lns[6]

    return lns[1], lns[4]
示例#7
0
def add_two_numbers(l1: ListNode, l2: ListNode) -> ListNode:
    dummy = ListNode()
    curr = dummy
    p1, p2 = l1, l2
    carrier = 0
    while p1 or p2:
        x = p1.val if p1 else 0
        y = p2.val if p2 else 0
        carrier, val = divmod(x + y + carrier, 10)
        curr.next = ListNode(val)
        curr = curr.next
        if p1:
            p1 = p1.next
        if p2:
            p2 = p2.next

    if carrier > 0:
        curr.next = ListNode(carrier)

    return dummy.next
示例#8
0
def reverse_kgroup(head: ListNode, k: int) -> ListNode:
    count = 0
    cur = head
    while cur:
        cur = cur.next
        count += 1
    if count < k:
        return head

    pre, new_head = reverse(head, k)
    head.next = reverse_kgroup(new_head, k)
    return pre
示例#9
0
def reverse_between(head: ListNode, m: int, n: int) -> ListNode:
    if m == 1:
        return reverse_n_wrapper(head, n)
    head.next = reverse_between(head.next, m - 1, n - 1)
    return head
示例#10
0
def ans():
    lns = {x: ListNode(x) for x in [5, 7, 9]}
    lns[5].next = lns[7]
    lns[7].next = lns[9]
    return lns[5]