/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *current = head;
ListNode *previous = 0;
if (!head->next && n == 1) {
return NULL;
}
//Count the list
int cnt = 0;
while(current) {
cnt++;
current = current->next;
}
//Find the target
current = head;
int index = 0;
while(current && cnt - n != index) {
index++;
previous = current;
current = current->next;
}
//Delete node
if (!previous) {
//If the target is the head
head = current->next;
} else {
//If the target is not the head
previous->next = current->next;
}
current = 0;
return head;
}
};