Skip to content

Linked List Front Back Pointers

Table of Contents

19. Remove Nth Node From End of List

  • LeetCode | LeetCode CH (Medium)

  • Tags: linked list, two pointers

  • Given the head of a linked list, remove the n-th node from the end of the list and return its head.
19. Remove Nth Node From End of List - Python Solution
from typing import Optional

from template import ListNode


# Linked List
def removeNthFromEnd(head: Optional[ListNode], n: int) -> Optional[ListNode]:
    dummy = ListNode(0, head)
    fast, slow = dummy, dummy

    for _ in range(n):
        fast = fast.next

    while fast.next:
        fast = fast.next
        slow = slow.next

    slow.next = slow.next.next

    return dummy.next


head = [1, 2, 3, 4, 5]
n = 2
head = ListNode.create(head)
print(head)  # 1 -> 2 -> 3 -> 4 -> 5
print(removeNthFromEnd(head, n))  # 1 -> 2 -> 3 -> 5

61. Rotate List

1721. Swapping Nodes in a Linked List

1474. Delete N Nodes After M Nodes of a Linked List

1474. Delete N Nodes After M Nodes of a Linked List - Python Solution
from typing import Optional

from template import ListNode


# Linked List
def deleteNodes(
    head: Optional[ListNode], m: int, n: int
) -> Optional[ListNode]:
    dummy = ListNode(0, head)
    cur = dummy

    while cur.next:
        for _ in range(m):
            if not cur.next:
                break
            cur = cur.next

        for _ in range(n):
            if not cur.next:
                break
            cur.next = cur.next.next

    return dummy.next


if __name__ == "__main__":
    head = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
    m = 2
    n = 3
    head = ListNode.create(head)
    print(head)
    # 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> 11 -> 12 -> 13
    head = deleteNodes(head, m, n)
    print(head)
    # 1 -> 2 -> 6 -> 7 -> 11 -> 12

Comments