第一种方法:先遍历一遍取得长度,然后长度减去n就知道要删除正着数第几个节点,注意,我这里一直卡在,想找到要删除的第len-n个,只能循环cur=cur->next;len-n-1遍,才能将cur指针刚好指在要删除的节点的前一个。所以就会有两种情况会不进
for(int i=1;i<=len-n-1;i++)
cur=cur->next;
循环,第一种要删除的是正数第一个并且满足len=n,返回head->next就行;第二种是要删除的是正数第二个(此时cur指向head)可以和其他情况一起删除,利用
cur->next=cur->next->next;
因此完整代码如下,Runtime: 9 ms You are here! Your runtime beats 93.79 % of cpp submissions.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len=0;
ListNode *cur=head;
while(cur!=NULL)
{
len++;
cur=cur->next;
}
cur=head;
for(int i=1;i<=len-n-1;i++)
cur=cur->next;
if(cur==head&&n==len)
return head->next;
cur->next=cur->next->next;
return head;
}
};
第二种方法:用两个指针,一个快指针先走n步,一个慢指针从头开始走,这样当快指针走到尾部的时候,慢指针所指的就是要删除元素的前一个元素。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *first=head;
for(int i=1;i<=n;i++)
first=first->next;
if(first==NULL)
return head->next;
ListNode *second=head;
while(first->next!=NULL)
{
first=first->next;
second=second->next;
}
second->next=second->next->next;
return head;
}
};