1.双指针遍历法
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(head==nullptr) {
return head;
}
ListNode* fast = head;
for(int i=0;i<n;i++) {
fast = fast->next;
}
if(fast==nullptr) {
return head->next;
}
ListNode* slow = head;
while(fast->next) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};