19.删除链表的倒数第N个结点

双指针

如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾(NULL)。删掉slow所指向的节点就可以了,为了方便删除,使slow指向要删除结点的前一结点,所以一开始slow指向dummyhead,fast指向head结点。

  1. class Solution {
  2. public:
  3. ListNode* removeNthFromEnd(ListNode* head, int n) {
  4. ListNode* dummyhead = new ListNode(0,head);
  5. ListNode* slow =dummyhead;
  6. ListNode* fast = head;
  7. while(n-- && fast)
  8. fast=fast->next;
  9. while(fast)
  10. {
  11. slow = slow->next;
  12. fast=fast->next;
  13. }
  14. slow->next = slow->next->next;
  15. return dummyhead->next;
  16. }
  17. };