题目:
代码:
// 方法1:两次遍历,先确定链表的长度。
// 之后再根据n序号,删除特定指针
// 此方法需要判断链表长度为1的情况 、 删除头指针、删除尾指针三种特殊情况
// 方法2:快慢指针
// 1 : 要设置虚拟节点dummpyHead 指向 head
// 2 : 设定双指针fast 和 slow,初始都指向虚拟头节点dummpy Head
// 3 : 移动fast指针,直到fast 与 slow之间间隔n个节点
// 4 : 同时移动fast 与 slow节点,直到fast为unullptr
// 5 : 将slow的下一个节点指向下下个节点
/**
* 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:
// ListNode* removeNthFromEnd(ListNode* head, int n) {
// if(head == nullptr || head->next == nullptr) return nullptr;
// int count = 0;
// ListNode* index = head;
// while(index != nullptr) {
// count++;
// index = index->next;
// }
// index = head;
// // 针对两种特殊情况进行判断
// if(count == n) { // 删除头指针
// index = index->next;
// return index; // 此处不返回,就无法覆盖head!!!
// } else {
// int count_de = count - n - 1;
// while(count_de--) {
// index = index->next;
// }
// if(n == 1) // 删除尾指针
// index->next = nullptr;
// else
// index->next = index->next->next;
// }
// return head;
// }
// };
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// 构造虚拟头节点
ListNode* dummpy_head = new ListNode(-1);
dummpy_head->next = head;
// 构造快慢指针分别指向虚拟头指针
ListNode* fast = dummpy_head;
ListNode* slow = dummpy_head;
// 确保快慢指针之间间隔2个节点
for(int i = 0; i < n+1; i++) {
fast = fast->next;
}
// 移动slow指针到要删除的节点
while(fast) {
fast = fast->next;
slow = slow->next;
}
// 删除指针
slow->next = slow->next->next;
return dummpy_head->next;
}
};