2026/02/23

[LeetCode] 19 Remove Nth Node From End of List

判斷被刪掉是否是head

稍微有點繞


  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. const int MAGIC = 55668787;
  14. ListNode* removeNthFromEnd(ListNode* head, int n) {
  15. ListNode* slowNode = head;
  16. ListNode* prevNode = new ListNode(MAGIC, slowNode);
  17. ListNode* fastNode = head;
  18. // step 1 : find n-th node from the end
  19. for (int i = 0; i < n; i++)
  20. fastNode = fastNode->next;
  21. while (fastNode != nullptr) {
  22. prevNode = slowNode;
  23. slowNode = slowNode->next;
  24. fastNode = fastNode->next;
  25. }
  26. // Step 2 : Remove slowNode
  27. // In this moment, slowNode is the n-th node from the end
  28. prevNode->next = slowNode->next;
  29. if (slowNode == head)
  30. if (slowNode->next == nullptr)
  31. return nullptr;
  32. else
  33. return prevNode->next;
  34. else
  35. return head;
  36. }
  37. };