class Solution
{
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode** t1 = &head, *t2 = head;
for(int i = 1; i < n; ++i)
{
t2 = t2>next;
}
while(t2>next != NULL)
{
t1 = &((*t1)>next);
t2 = t2>next;
}
*t1 = (*t1)>next;
return head;
}
};
My short C++ solution


Your solution is very smart!!! But the double pointer let me difficult to understand. So I rewrite you solution.
Thank for your solution.ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* ans; ListNode* slow = head; //t1 ListNode* fast = head; //t2 for(int i=0;i<n;++i) { fast = fast>next; } if(fast == NULL) { ans = head>next; delete head; return ans; } while(fast>next != NULL) { fast = fast>next; slow = slow>next; } delete slow>next; slow>next = slow>next>next; return head; }

Thanks for sharing.
Here is a recursive solution.code:
int countAndRemove(struct ListNode *node, int n){ //Once the stack frame reaches the tail, counting starts. if(!node>next) return n1; int NumOfNodesLeft = countAndRemove(node>next, n); //If there are exactly n nodes in the rest of the list, delete next node. if(NumOfNodesLeft == 0) node>next = (node>next)>next; //Count decremented. return NumOfNodesLeft  1; } struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { return (countAndRemove(head, n) == 0)? head>next : head; }
The idea is based on how function call, namely pushing and popping stack frames, works.
i) Push as many stack frames as the size of linked list. so n is passed to the end (top frame). ii) As the last frame pops off, counting begins.
Suppose there S nodes in the linked list.
The stack frames would be like the following:
===================================================
Sth stack: 1st node ( counting from the back ) n = n, NumOfNodesLeft = n, return n  1.
===================================================
(S1)th stack: 2nd node ( from the back ), n = n, NumOfNodesLeft = n  1, return n  2.
===================================================
:
===================================================
(Sn1)th stack: 2nd node ( from the back ), n = n, NumOfNodesLeft = 0, return 1.
Only this frame does the deletion.
===================================================
:
===================================================
Second stack: (S1)Th node ( counting from the back ), NumOfNodesLeft = n  (S 1), return n  (S1)  1.
===================================================
First stack: Sth node from the back / 1st node in the list, NumOfNodesLeft = n  S, return n  S  1.
===================================================