首页 > 代码库 > [Leetcode] 19 - Remove Nth Node From End of List

[Leetcode] 19 - Remove Nth Node From End of List

原题链接:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/


这道题是移除倒数第n个node,做法是保持2个指针,一快一慢,快指针先走n步,然后快慢指针同时走,直到快指针变成null。这时将慢指针的值改为next的值。(注意,慢指针其实是指针的指针,以为为了改变指向当前node的指针的值)。个人感觉这题其实要非常仔细做才行,不然很容易写错。属于想法简单,但是需要仔细和强大的内心。


/**
 * 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* fast = head;
        ListNode** slowpp = NULL;
        
        int i = 0;
        while (fast) {
            fast = fast->next;
            
            ++i;
            if (i == n) {
                slowpp = &head;
            } else if (i > n) {
                slowpp = &((*slowpp)->next);
            } 
        }
        
        if (*slowpp) {
            ListNode* next = (*slowpp)->next;
            ListNode* cur = (*slowpp);
            delete(cur);
            *slowpp = next;
        }
        
        return head;
    }
};


[Leetcode] 19 - Remove Nth Node From End of List