题目描述[简单]:
题解:
求得链表长度,得出正向遍历的次数,使用快慢指针,删除对应结点
/**
* 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:
int getlen(ListNode* head)
{
int count = 0;
while(head != NULL)
{
++count;
head = head->next;
}
return count;
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(n <= 0) return nullptr;
ListNode* fast = head;
ListNode* slow = NULL;
int forward = getlen(head) - n;
if(forward == 0) return head->next;
while(forward--)
{
slow = fast;
fast = fast->next;
}
slow->next = fast->next;
return head;
}
};