题目描述

在这里插入图片描述

题解

求得链表长度,得出正向遍历的次数,使用快慢指针,删除对应结点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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;
}
};