Remove Nth Node From End of List

描述

Given a linked list, remove the n-th node from the end of list and return its head.

For example, Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

  • Given n will always be valid.
  • Try to do this in one pass.

    分析

设两个指针p,q,让q先走n步,然后pq一起走,直到q走到尾节点,删除p->next即可。

代码

  1. // Remove Nth Node From End of List
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *removeNthFromEnd(ListNode *head, int n) {
  6. ListNode dummy{-1, head};
  7. ListNode *p = &dummy, *q = &dummy;
  8. for (int i = 0; i < n; i++) // q先走n步
  9. q = q->next;
  10. while(q->next != nullptr) { // 一起走
  11. p = p->next;
  12. q = q->next;
  13. }
  14. ListNode *tmp = p->next;
  15. p->next = p->next->next;
  16. delete tmp;
  17. return dummy.next;
  18. }
  19. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/linked-list/remove-nth-node-from-end-of-list.html