Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.

http://www.lintcode.com/en/problem/remove-nth-node-from-end-of-list/

Solution


不难,就是Nth to Last Node in List问题的基础上多了一个remove操作。

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // write your code here
        if(head==NULL || n<0) return head;
        ListNode dummy(-1);
        dummy.next = head;
        ListNode *first = &dummy;
        ListNode *second = &dummy;
        ListNode *preSec = &dummy;
        while(n>0 && first!=NULL) {
            first = first->next;
            n--;
        }
        if(first == NULL)
            return head;
        while(first != NULL) {
            first = first->next;
            preSec = second;
            second = second->next;
        }
        preSec->next = second->next;
        delete second;
        second = NULL;
        return dummy.next;
    }
};

results matching ""

    No results matching ""