
Input: head =[1,2,3,4,5,6,7,8,9,10,11,12,13], m =2, n =3Output: [1,2,6,7,11,12]Explanation: Keep the first(m =2) nodes starting from the head of the linked List(1->2) show in black nodes.Delete the next(n =3) nodes (3->4->5) show in read nodes.Continue with the same procedure until reaching the tail of the Linked List.Head of the linked list after removing nodes is returned.
Example 2:
1
2
3
4

Input: head =[1,2,3,4,5,6,7,8,9,10,11], m =1, n =3Output: [1,5,9]Explanation: Head of linked list after removing nodes is returned.
Constraints:
The number of nodes in the list is in the range [1, 10^4].
1 <= Node.val <= 10^6
1 <= m, n <= 1000
Follow up: Could you solve this problem by modifying the list in-place?
We can solve this problem by traversing the linked list and, for each segment, keeping the first m nodes and then deleting the next n nodes. We repeat this process until the end of the list. This approach modifies the list in-place and is efficient for large lists.
classSolution {
public: ListNode* deleteNodes(ListNode* head, int m, int n) {
ListNode* cur = head;
while (cur) {
for (int i =1; i < m && cur; ++i) cur = cur->next;
if (!cur) break;
ListNode* tmp = cur->next;
for (int i =0; i < n && tmp; ++i) tmp = tmp->next;
cur->next = tmp;
cur = tmp;
}
return head;
}
};
classSolution {
public ListNode deleteNodes(ListNode head, int m, int n) {
ListNode cur = head;
while (cur !=null) {
for (int i = 1; i < m && cur !=null; i++) cur = cur.next;
if (cur ==null) break;
ListNode tmp = cur.next;
for (int i = 0; i < n && tmp !=null; i++) tmp = tmp.next;
cur.next= tmp;
cur = tmp;
}
return head;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
fundeleteNodes(head: ListNode?, m: Int, n: Int): ListNode? {
var cur = head
while (cur !=null) {
for (i in1 until m) {
if (cur?.next ==null) return head
cur = cur.next
}
var tmp = cur?.next
for (i in0 until n) {
if (tmp ==null) break tmp = tmp.next
}
cur?.next = tmp
cur = tmp
}
return head
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defdeleteNodes(self, head: 'ListNode', m: int, n: int) ->'ListNode':
cur = head
while cur:
for _ in range(m -1):
ifnot cur:
return head
cur = cur.next
ifnot cur:
break tmp = cur.next
for _ in range(n):
ifnot tmp:
break tmp = tmp.next
cur.next = tmp
cur = tmp
return head