题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
#include <stdlib.h>
int countList(struct ListNode* head)
{
int cnt = 0;
while(head)
{
head= head->next;
cnt++;
}
return cnt;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) {
// write code here
struct ListNode* tmp = NULL;
struct ListNode* tmp_pre = NULL;
int cnt = countList(head);
int index = cnt -n;
tmp = tmp_pre = head;
while (index--) {
tmp_pre=tmp;
tmp=tmp->next;
}
if(head==tmp)
{
head = tmp->next;
}
else {
tmp_pre->next = tmp->next;
free(tmp);
}
return head;
}

