题解 | #删除链表的倒数第n个节点#
//定义一个哨兵位头结点,方便记录prev
//先求出cur要前移的次数,然后通过prev删除
struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) {
// write code here
if(head==NULL)
{
return head;
}
struct ListNode* node=head;
struct ListNode* H=(struct ListNode*)malloc(sizeof(struct ListNode));
H->next=head;
struct ListNode* prev=H;
struct ListNode* cur=head;
int leng=0;
while(node)
{
node=node->next;
leng++;
}
int num=leng-n;
while(num--)
{
cur=cur->next;
prev=prev->next;
}
prev->next=cur->next;
return H->next;
}