思路:本题先查找到倒数的第n个节点,用slow存储这个点的位置,相关解发参考算法上一道题,找到后用一个变量tail存储这个n点的前一位,再将tail的next指向改变为slow的next,注意有内存泄漏所以要加上n是不是头结点的位置,如果是则改变头的指向。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) {
if(head==NULL)
return NULL;
struct ListNode*fast=head,*slow=head,*tail=NULL;
for(int i=0;i<n;i++)
{
fast=fast->next;
}
while(fast!=NULL)
{
tail=slow;
slow=slow->next;
fast=fast->next;
}
if(slow==head) //slow代表第n个结点的位置,在这里进行判断如果是的则头删。
{
head=head->next;
}
else
{
tail->next=slow->next;
free(slow);
slow->next=NULL;
}
return head;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n ) {
if(head==NULL)
return NULL;
struct ListNode*fast=head,*slow=head,*tail=NULL;
for(int i=0;i<n;i++)
{
fast=fast->next;
}
while(fast!=NULL)
{
tail=slow;
slow=slow->next;
fast=fast->next;
}
if(slow==head) //slow代表第n个结点的位置,在这里进行判断如果是的则头删。
{
head=head->next;
}
else
{
tail->next=slow->next;
free(slow);
slow->next=NULL;
}
return head;
}