# Remove Nth Node From End of List [closed]

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

ListNode *removeNthFromEnd(ListNode *head, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return NULL;
}

ListNode *pre, *cur;
for (int i = 0; i < n; ++i) {
pre = pre->next;
}

while (pre != NULL && pre->next != NULL) {
cur = cur->next;
pre = pre->next;
}

//mistake
// I use the above line to check if it's the first node to be deleted,
// there is a problem for this case: list: 1->2, n : 1
if (pre == NULL) {
}
else {
ListNode *tmp = cur->next;
cur->next = tmp->next;
delete tmp;
}
}


## closed as off-topic by Mathieu Guindon, Jamal♦, Malachi♦, Kinjal, palacsintNov 17 '13 at 8:10

If this question can be reworded to fit the rules in the help center, please edit the question.

• This question appears to be off-topic because it is not clear whether it's asking for code to be written; also the code being embedded in a block quote makes it looks like it's not the OP's code. – Mathieu Guindon Nov 17 '13 at 3:16
• @retailcoder: Based on the tag, I assume this was straight from the interviewer. But I cannot tell for sure, so I agree with your close reason. – Jamal Nov 17 '13 at 3:37

Your function fails if n is 0 or greater than the list size.

Also, I prefer to see one variable defined per-line:

ListNode *pre = head;

BTW, delete is C++, not C