Monday, November 25, 2013

LeetCode Problem : Remove Nth Node From End of List

Problem

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.
Note:
Given n will always be valid.
Try to do this in one pass.

Code

ListNode *removeNthFromEnd(ListNode *head, int n) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int count = 0;
    ListNode * node = head;
    while( node && count < n){
        node = node->next;
        ++count;
    }
    if(node == 0 && count == n){
        ListNode *temp = head->next;
        delete head;
        head = temp;
    }
    else if(node == 0)
        return head;
    else{
        ListNode *prev = head;
        while(node->next){
            node = node->next;
            prev = prev->next;
        }
        ListNode *temp = prev->next;
        prev->next = temp->next;
        delete temp;
    }
    return head;
}

No comments:

Post a Comment