优化
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!n)return head;
ListNode* order=nullptr;
int num=0;
auto h=head;
while(head){
num++;
cout<<num<<" "<<head->val<<endl;
if(num==n+1)order=h;
else if(num>n+1){
order=order->next;
};
head=head->next;
}
if(num==n)return h->next;
if(n==1)order->next=nullptr;
else order->next=order->next->next;
return h;
}
};
队列
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
queue<ListNode*>q;
if(!n)return head;
auto h=head;
while(head){
q.emplace(head);
if(q.size()>n+1)q.pop();
head=head->next;
}
if(q.size()==n)return h->next;
if(n==1)q.front()->next=nullptr;
else{
auto temp=q.front();
q.pop();
temp->next=q.front()->next;
}
return h;
}
};