[LeetCode] Delete N Nodes After M Nodes of a Linked List

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

You are given the head of a linked list and two integers m and n.

Traverse the linked list and remove some nodes in the following way:

  • Start with the head as the current node.
  • Keep the first m nodes starting with the current node.
  • Remove the next n nodes
  • Keep repeating steps 2 and 3 until you reach the end of the list.

Return the head of the modified list after removing the mentioned nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteNodes(ListNode* head, int m, int n) {
ListNode *res = head, *runner = head;
while(runner) {
for(int i = 0; i < m - 1 and runner; i++) runner = runner->next;
if(!runner) break;
ListNode* tail = runner;
runner = runner->next;
for(int i = 0; i < n and runner; i++) runner = runner->next;
tail->next = runner;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/delete-n-nodes-after-m-nodes-of-a-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.