LeetCode 1474: Delete N Nodes After M Nodes of a Linked List
Problem Description
Explanation:
To solve this problem, we can iterate through the linked list and skip M
nodes, then delete the next N
nodes. We need to be careful to handle edge cases where the list may not have enough nodes to delete.
- Initialize a pointer
current
to the head of the linked list. - Iterate through the list, skipping
M
nodes and deleting the nextN
nodes until the end of the list is reached. - Ensure to update the next pointers appropriately to connect the nodes after deletion.
Time Complexity: O(N), where N is the number of nodes in the linked list. Space Complexity: O(1)
:
Solutions
class Solution {
public ListNode deleteNodes(ListNode head, int m, int n) {
ListNode current = head;
while (current != null) {
int countM = m, countN = n;
while (current != null && countM > 1) {
current = current.next;
countM--;
}
ListNode toDelete = current.next;
while (toDelete != null && countN > 0) {
toDelete = toDelete.next;
countN--;
}
if (current != null) {
current.next = toDelete;
current = toDelete;
}
}
return head;
}
}
Loading editor...