LeetCode19 删除节点的倒数第n个节点

题目:
在这里插入图片描述
过程如图所示:
在这里插入图片描述
设定两个指针,first指针先从dummy出发走n步,然后,first和second一起走完剩下的路程,最后second删除它指向的下一个节点就可以了。这个即是常用的快慢指针的用法。
代码如下:

/**
 * 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 * dummy = new ListNode(-1);
        dummy->next = head;
        ListNode * first = dummy, *second = dummy;
        for(int i = 0; i < n; i++){
    
    
            first = first->next;
        }
        while(first->next){
    
    
            first = first->next;
            second = second->next;
        }
        second->next = second->next->next;
        return dummy->next;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44879626/article/details/107936373