Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:

Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1 Output: []
Example 3:
Input: head = [1,2], n = 1 Output: [1]
/**
* 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) {
ListNode *sta = new ListNode(0);
ListNode *slow =sta;
ListNode *fast = sta;
slow->next = head;
for (int i=0;i<n;i++)
fast=fast->next;
while (fast->next){
fast = fast->next;
slow =slow->next;
}
slow->next =slow->next->next;
return sta->next;
}
};
该博客介绍了一个C++实现的解决方案,用于从单链表中删除第n个从尾部开始的节点。通过使用两个指针,一个快指针先移动n步,然后两个指针同步移动直到快指针到达链表末尾,此时慢指针指向要删除的节点的前一个位置,从而可以安全地移除目标节点。
641

被折叠的 条评论
为什么被折叠?



