这个我的程序写的是有些复杂的,但是整体原理简单
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* res=head;
int length=0;
while(res!=NULL){
length++;
res=res->next;
}
//只有一个的时候直接删掉
if(length==1) return {};
//要删除的是第一个的时候特殊处理
if(length==n){
head=head->next;
return head;
}
res=head;
int i=1;
while(res!=NULL&&length-i>n){
res=res->next;
i++;
}
res->next=res->next->next;
return head;
}
};
京公网安备 11010502036488号