虽然题目对于边界条件有限定,但是这里还是考虑各种边界异常情况
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (n <= 0 || head == nullptr) {
return head;
}
// 头节点对于边界的处理很重要
ListNode *head_node = new ListNode(-1);
head_node->next = head;
ListNode *fast = head_node, *slow = head_node;
for (int i = 0; i < n && fast; i++) { // 先走 n 步
fast = fast->next;
}
if (fast == nullptr) { // n取值异常
return head;
}
while (fast->next) { // 走到倒数第一个节点
fast = fast->next;
slow = slow->next; // 指向倒数第 n+1 个节点
}
ListNode *tmp = slow->next;
slow->next = slow->next->next;
delete(tmp);
tmp = nullptr;
head = head_node->next;
delete(head_node);
head_node = nullptr;
return head;
}
};