我的算法-
private static MyList skip$DeleteItem(MyList L , int M , int N){
MyList curr = L;
MyList prev = null;
while(curr != null){
int counter = 0;
while(curr != null && counter <M){
prev = curr;
curr = curr.next;
counter++;
}
counter = 0;
while(curr != null && counter < N){
curr = curr.next;
if(prev == null){
prev = curr;
}
else{
prev.next = curr;
}
counter ++;
}
}
return L;
}
它适用于每个基本测试用例,但跳过值 0 和删除 1 失败。
输入 - 9-->34-->8-->7-->5-->4-->6-->3-->1-->2-->TAIL
输出 - 9-->34-->TAIL
预期 - NULL(因为所有元素都应该被删除)
解决方案是
while(curr != null && counter < N){
curr = curr.next;
if(prev == null){
curr = curr.next;
L = curr;
}
else{
prev.next = curr;
}
counter ++;
}