classSolution {
public ListNode deleteNodes(ListNode head, int x, int y) {
// Initialize a dummy node pointing to the head to handle edge cases// smoothly ListNode dummy =new ListNode(0);
dummy.next= head;
ListNode current = dummy;
// Traverse y nodes from the dummy nodefor (int i = 0; i < y; i++) {
if (current.next==null) {
return dummy.next; // If y is greater than the length of the// list, return the original list }
current = current.next;
}
// Now current is pointing to the y-th node, start deleting x nodes// after this node ListNode toDelete = current.next;
for (int i = 0; i < x; i++) {
if (toDelete ==null) {
break; // If there are not enough nodes to delete }
toDelete = toDelete.next;
}
// Connect the y-th node to the node after the deleted nodes current.next= toDelete;
return dummy.next;
}
}
defdeleteNodes(head: ListNode, x: int, y: int) -> ListNode:
# Initialize a dummy node pointing to the head to handle edge cases smoothly dummy = ListNode(0)
dummy.next = head
current = dummy
# Traverse y nodes from the dummy nodefor i in range(y):
if current.next isNone:
return (
dummy.next
) # If y is greater than the length of the list, return the original list current = current.next
# Now current is pointing to the y-th node, start deleting x nodes after this node to_delete = current.next
for i in range(x):
if to_delete isNone:
break# If there are not enough nodes to delete to_delete = to_delete.next
# Connect the y-th node to the node after the deleted nodes current.next = to_delete
return dummy.next