cztchoice
1/14/2014 - 10:44 AM

Remove Nth Node From End of List http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        /*ListNode * first = new ListNode(0);
        first->next = head;
        ListNode * fast = first;
        ListNode * slow = first;
        int i = n;
        while(i > 0){
            fast = fast->next;
            i--;
        }
        if(fast == NULL){
            return NULL;
        }
        while(fast->next != NULL){
            fast = fast->next;
            slow = slow->next;
        }
        ListNode * temp = slow->next;
        slow->next = temp->next;
        delete temp;
        
        head = first->next;
        delete first;
        return head;*/
        ListNode * fast = head;
        ListNode * slow = head;
        int i = n;
        while(i > 0){
            fast = fast->next;
            i--;
        }
        if(fast == NULL ){ // remove head 
            ListNode * temp = head;
            head = head->next;
            delete temp;
            return head;
        }
        while(fast->next != NULL){
            fast = fast->next;
            slow = slow->next;
        }
        ListNode * temp = slow->next;
        slow->next = temp->next;
        delete temp;
        
        return head;
    }
};