牛客上 题目给出的要比书上的简单,牛客上求的是删除第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;
}
这里需要注意的就是快慢指针遍历的过程中要不断判断后继和后继的后继是否为空。