
删除从后往前数的第n个节点
我的做法是将两个指针first,second
先将first指向第n-1个,然后让first和second一起指向他们的next,直到first->next->next为空
最后只要删除second->next
/**
* 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) return head; ListNode* first = head;
for(int i = ; i < n - ; first = first->next, ++i); if(!first->next){
first = head;
head = head->next;
delete first;
return head;
} ListNode* second= head;
for(;first->next->next; first = first->next, second = second->next); ListNode* next = second->next;
second->next = next->next;
delete next; return head;
}
};