class Solution {public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* pre = dummyHead; ListNode* cur = head; // pre与cur的索引插值保持为n 初始时pre为0,cur为1 while((--n)){ // cur先单独移动n个单位,如果n=1那么就不用移动了 cur = cur->next; } // cur直接移动到最后一个结点,此时pre->next就是要删除的结点 while(cur->next!=NULL){ pre = pre->next; cur = cur->next; } // 删除 ListNode* tmp = pre->next; pre->next = tmp->next; delete tmp; return dummyHead->next; }};