Friday, September 13, 2013

Delete nth Node from the last of Link 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.
Note:
Given n will always be valid.
Try to do this in one pass.
   ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(n <= 0  || !head)
                return head;
        // take slow pointer and fast pointer
        ListNode *slow = NULL;
        ListNode *fast = NULL;
        // move fast pointer to n nodes
        while(n > 0)
        {  
            if(!fast)
                fast = head;
            else 
                fast = fast->next;
         
            if(!fast)
                break;
            n--;
        }
        if(!fast)
            return head;
        fast = fast->next;
        // now move slow pointer and fast pointer
        ListNode *prevNode = NULL;
        slow = head;
        while(fast)
        {
            if(!prevNode)
            {
                prevNode = slow;
            }
            else {
                prevNode = prevNode->next;
            }
            fast = fast->next;
        }
        // now need  
        if(!prevNode)
            head =  head->next;
        else
            prevNode->next = prevNode->next->next;
        return head;
}

No comments:

Post a Comment