题目地址:
https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/
给定一个链表,再给定两个正整数 m m m和 n n n,进行如下操作,先保留前 m m m个节点,然后删去接下来的 n n n个节点,然后再保留 m m m个节点,再删去接下来的 n n n个节点,如此循环,直到走到链表结尾。
代码如下:
public class Solution {
public ListNode deleteNodes(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0), prev = dummy;
dummy.next = head;
while (true) {
for (int i = 0; i < m && prev != null; i++) {
prev = prev.next;
}
if (prev == null) {
break;
}
// 走到这儿的时候prev是要删除的n个节点的前面那个节点
ListNode forward = prev;
for (int i = 0; i < n && forward != null; i++) {
forward = forward.next;
}
if (forward == null) {
prev.next = null;
break;
}
prev.next = forward.next;
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n ) O(n) O(n), n n n为链表长度。