/**
* 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) {
if(head==NULL||n<=0){
return head;
}
ListNode *temp=head;
ListNode *slow=head;
ListNode *pre=NULL;
for(int i=0;i<n;++i){
if(temp){
temp=temp->next;
}else{
return NULL;
}
}
while(temp){
temp=temp->next;
pre=slow;
slow=slow->next;
}
if(pre==NULL){
head=head->next;
return head;
}
pre->next=slow->next;
slow=NULL;
return head;
}
};
链表中删除倒数第n个
最新推荐文章于 2023-03-30 12:46:08 发布