给定链表 head 和两个整数 m 和 n. 遍历该链表并按照如下方式删除节点:
开始时以头节点作为当前节点. 保留以当前节点开始的前 m 个节点. 删除接下来的 n 个节点. 重复步骤 2 和 3, 直到到达链表结尾. 在删除了指定结点之后, 返回修改过后的链表的头节点.
进阶问题: 你能通过就地修改链表的方式解决这个问题吗?
C++
class Solution {
public:
ListNode
* deleteNodes(ListNode
* head
, int m
, int n
) {
auto cur_node
=head
;
auto cur_head
=head
;
while(cur_node
){
for(int i
=0;i
<m
-1 && cur_node
;++i
){
cur_node
=cur_node
->next
;
}
if(cur_node
){
cur_head
=cur_node
;
cur_node
=cur_node
->next
;
}
for(int i
=0;i
<n
&& cur_node
;++i
){
cur_head
->next
=cur_node
->next
;
delete cur_node
;
cur_node
=cur_head
->next
;
}
}
return head
;
}
};