Remove Nth Node From End of List
题目:
Given a linked list, remove the nth node from the end of list and return its head.
The minimum number of nodes in list is n.
Example Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.
分析:
从这个题目中就学到一件事,从dummy开始做,一切都好,从head开始做,什么都完蛋!
解法:
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) {
            return NULL;
        }
        ListNode dummy(-1);
        dummy.next = head;
        ListNode* slow = &dummy;
        ListNode* fast = &dummy;
        for (int i = 0; i < n; i++) {
            fast = fast->next;
        }
        while (fast->next != NULL) {
            slow = slow->next;
            fast = fast->next;
        }
        slow->next = slow->next->next;
        return dummy.next;
    }
};