双指针
/**
* 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) {
ListNode ans(0);
ans.next = head;
ListNode *after = &ans, *now = &ans;
for(int i = 0; i < n; i++) {
after = after->next;
}
while(after->next){
now = now->next;
after = after->next;
}
now->next = now->next->next;
return ans.next;
}
};
题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/