Remove Nth Node From End of List 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
    if (head == NULL) {
      return NULL;
    }

    ListNode *pre, *cur;
    pre = cur = head;
    for (int i = 0; i &lt; n; ++i) {
      pre = pre-&gt;next;
    }

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

  //mistake
  //if (cur == head) {
  // 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-&gt;2, n : 1
    if (pre == NULL) {
      ListNode *newHead = head-&gt;next;
      delete head;
      return newHead;
    }
    else {
      ListNode *tmp = cur-&gt;next;
      cur-&gt;next = tmp-&gt;next;
      delete tmp;
      return head;
    }        
}
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;
ListNode *cur = head;


And the opening brace belongs in column 0 (I guess you don't agree, but there are - or were anyway - tools that rely on this).

An alternative implementation might use a function to find the number of entries in the list and another to return a specified entry (size - n - 1, in this case). Then once you've checked that 0 &lt; n &lt;= size, the main function is simple - but no better than yours :-)

BTW, delete is C++, not C