Skip to main content
Post Closed as "Not suitable for this site" by Mathieu Guindon, Jamal, Malachi, Kinjal, palacsint
edited tags
Link
Fihop
  • 1k
  • 4
  • 20
  • 31
Tweeted twitter.com/#!/StackCodeReview/status/314825322350641154
Source Link
Fihop
  • 1k
  • 4
  • 20
  • 31

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