C++
计算长度
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * dumHead = new ListNode(0);
dumHead->next = head;
ListNode * cur = dumHead;
int length = 0;
while(cur->next != nullptr){
cur = cur->next;
length ++;
}
int a = length - n;
cur = dumHead;
while(a > 0){
cur = cur->next;
a--;
}
ListNode * tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp = nullptr;
return dumHead->next;
}
};
双指针:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * dumHead = new ListNode(0);
dumHead->next = head;
ListNode * slow = dumHead;
ListNode * fast = dumHead;
while(n-- && fast != nullptr){
fast = fast->next;
}
while(fast->next != nullptr){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dumHead->next;
}
};
递归
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == nullptr)
{
return head;
}
head->next =removeNthFromEnd(head->next, n);
count++;
return count == n ? head->next: head;
}
int count = 0;
};