Delete n nodes after m nodes of a linked list

December 19, 2022

linked-list

Problem URL: Delete n nodes after m nodes of a linked list

We will create a dummy node and attach the head node to it. Then we will do the following:

class Solution:
    def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode:
        dummy = ListNode(0, head)
        i = 0
        while head:
            if i < m-1:
                i += 1
            elif i == m-1:
                for _ in range(n):
                    if head.next:
                        head.next = head.next.next
                i = 0
            head = head.next
        return dummy.next

Time complexity: O(n)
Space complexity: O(1)