Remove Nth Node From End of List

 

    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(!head||n<=0)
            return NULL;
        int i;
        ListNode* slow,*fast,*prev=NULL;
        slow = fast = head;
        for(i=0;i<n-1;i++)
            fast = fast->next;
        while(fast->next)
        {
            fast = fast->next;
            prev = slow;
            slow = slow->next;
        }
        
        if(!prev)
        {
            ListNode* newHead = head->next;
            delete head;
            return newHead;
        }else
        {
            prev->next = slow->next;
            delete slow;
            return head;
        }
        
        
        
    }

  

posted @ 2013-10-06 14:09  summer_zhou  阅读(131)  评论(0编辑  收藏  举报