判斷被刪掉是否是head
稍微有點繞
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- const int MAGIC = 55668787;
- ListNode* removeNthFromEnd(ListNode* head, int n) {
- ListNode* slowNode = head;
- ListNode* prevNode = new ListNode(MAGIC, slowNode);
- ListNode* fastNode = head;
- // step 1 : find n-th node from the end
- for (int i = 0; i < n; i++)
- fastNode = fastNode->next;
- while (fastNode != nullptr) {
- prevNode = slowNode;
- slowNode = slowNode->next;
- fastNode = fastNode->next;
- }
- // Step 2 : Remove slowNode
- // In this moment, slowNode is the n-th node from the end
- prevNode->next = slowNode->next;
- if (slowNode == head)
- if (slowNode->next == nullptr)
- return nullptr;
- else
- return prevNode->next;
- else
- return head;
- }
- };