难度:中等。
双指针,重点是思路,实现简单。
正确解法:
/**
* 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 == NULL)return head;
if(head->next == NULL && n == 1)return NULL;
ListNode * result = head, *temp = head;
for(int i = 0; i < n; i++){
temp = temp -> next;
}
if(temp == NULL){
return head->next;
}
while(temp->next != NULL){
result = result->next;
temp = temp->next;
}
result->next = result->next->next;
return head;
}
};