remove nth node from end of list

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if( head == NULL ) return head;
        
        ListNode * root = new ListNode(-1);
        root->next = head;
        while( n>0&& head != NULL )
        {
            head = head->next;
            n--;
        }
        ListNode * h = root;
        ListNode * ptr = root->next;
        while( head != NULL )
        {
            ptr=ptr->next;
            head = head->next; 
            h = h->next;
        }
        h->next = ptr -> next;
        
        return root->next;
    }
};

 

posted on 2013-07-05 19:56  jumping_grass  阅读(115)  评论(0)    收藏  举报

导航