牛客上 题目给出的要比书上的简单,牛客上求的是删除第k个节点,所以只需要找到第k-1个即可。先写牛客上的内容
list_node * remove_kth_node(list_node * head, int K)
{
//////在下面完成代码
list_node* cur=head;
list_node* pre=head;
if(K==1){
return head->next;
}
while(--K){
pre=cur;
cur=cur->next;
}
pre->next=pre->next->next;
return head;
}
书上先求的是删除中间节点,那么如何找到中间节点呢。快慢指针
ListNode* removeMidNode(ListNode* head){
if(head->next==NULL||head->next==NULL){
return head;
}
if(head->next->next==NULL){
return head->next;
}
ListNode* slow=head;
ListNode* fast=head->next->next;
while(fast->next!=NULL&&fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
slow->next=slow->next->next;
return head;
}
这里需要注意的就是快慢指针遍历的过程中要不断判断后继和后继的后继是否为空。

这篇博客探讨了如何通过快慢指针在链表中删除指定位置的节点。首先介绍了牛客网上的题目,该题目要求删除第k个节点,解决方案是找到第k-1个节点并更新其next指针。接着,博客详细解释了如何找到链表的中间节点,同样利用快慢指针,快指针每次前进两步,慢指针每次前进一步,当快指针无法继续前进时,慢指针即指向中间节点。这种方法适用于删除链表的中间节点。
419

被折叠的 条评论
为什么被折叠?



