这道题是2009年考研数据结构的真题,且是最后一道大题
分析:
第一次用python来写的时候,没有想到比较好的方法,先遍历一遍数出链表长度,找到倒数的那个位置,再遍历一遍进行删除;
第二次用c++来写的时候,为了尽量满足只遍历一遍的要求,用双指针的方法来写,两个指针之间的间距为n,感觉效果还是可以的;
c++代码
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* cur=head;
ListNode* start=head;
int i=0;
for(i=0;i<n;i++){
cur=cur->next;
}
if(cur==nullptr){
return head->next;
}
while(cur->next!=nullptr){
head=head->next;
cur=cur->next;
}
head->next=head->next->next;
return start;
}
};