删除单链表中倒数第k个结点c语言
时间: 2023-12-12 09:05:25 浏览: 106
C++实现单链表删除倒数第k个节点的方法
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode *fast = head, *slow = head;
for(int i = 0; i < n; i++){
fast = fast->next;
}
if(fast == NULL){ //需要删除的是头结点
head = head->next;
free(slow);
return head;
}
while(fast->next != NULL){
fast = fast->next;
slow = slow->next;
}
struct ListNode* temp = slow->next;
slow->next = slow->next->next;
free(temp);
return head;
}
阅读全文