要求:如题
思路:这种第n个可以用快慢指针,注意头也会删,所以统一搞个新的头
/**
* 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 *h=new ListNode(1,head);
ListNode *pre=h,*cur=h;
while(n--)cur=cur->next;
while(cur->next!=nullptr){
cur=cur->next;
pre=pre->next;
}
pre->next=pre->next->next;
return h->next;
}
};