Tuesday, January 8, 2013

Remove nth node from end of link list

Solution:


/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head == NULL)
            return head;

        ListNode *first = head, *second = head;
     
        while (n > 0) {
            second = second->next;
            n--;
        }
        while (second != NULL && second->next != NULL ) {
                second = second->next;
                first = first->next;
        }

        if (second == NULL) {
             head = first->next;
        } else if (first->next != NULL ) {
            first->next = first->next->next;
        } else {
            return NULL;
        }
        return head;
    }
};

==== Second Time ====
/**
 * 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 *curr = head, *trvs = head;
        if (head == NULL)
            return head;
        while (n-- > 0) {
            if (trvs -> next != NULL)
                trvs = trvs -> next;
            else // edge case where 1 -> 2 and n = 2.
                return head -> next;
        }
        
        while (trvs -> next != NULL) {
            trvs = trvs -> next;
            curr = curr -> next;
        }
        // At this point, curr is always having curr -> next;
        assert(curr -> next);
        curr -> next = curr -> next -> next;
        return head;
    }
};

No comments:

Post a Comment