C++速通LeetCode中等第18题-删除链表的倒数第N个结点(最简单含注释)

绝妙!快慢指针法,快指针先走n步(复杂度O(n),O(1)):

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        //设定快慢指针,速度都是1,但是快指针先走n步,慢指针再同时出发,这样一来快指针到结尾时,慢指针到达指定位置
        ListNode* fast = head;
        ListNode* slow = head;
        for(int i = 0; i < n; i++) fast = fast->next;
        if(!fast) return head->next;//n=节点数时,不用移动了,特殊情况直接返回头节点的下一个
        while(fast && fast->next)
        {
            fast = fast->next;
            slow = slow->next;
        }//循环结束的slow就是答案要求的起始位置
        if(!slow->next) return nullptr;
        slow->next = slow->next->next;
        return head;
    }
};
相关推荐
%xiao Q14 小时前
GESP C++四级-216
java·开发语言·c++
tianyuanwo14 小时前
深入浅出SWIG:从C/C++到Python的无缝桥梁
c语言·c++·python·swig
程序员-King.14 小时前
day151—双端队列—找树左下角的值(LeetCode-513)
算法·leetcode·二叉树·双端队列·队列
苦藤新鸡14 小时前
15 .数组右移动k个单位
算法·leetcode·动态规划·力扣
氷泠15 小时前
路径总和系列(LeetCode 112 & 113 & 437 & 666)
leetcode·前缀和·深度优先·路径总和
初次见面我叫泰隆15 小时前
Qt——2、信号和槽
开发语言·c++·qt
D_evil__15 小时前
【Effective Modern C++】第二章 auto:5. 优先使用 auto,而非显式类型声明
c++
玖釉-15 小时前
[Vulkan 学习之路] 26 - 图像视图与采样器 (Image View and Sampler)
c++·windows·图形渲染
一颗青果15 小时前
C++的锁 | RAII管理锁 | 死锁避免
java·开发语言·c++
AI视觉网奇15 小时前
ue c++ 编译常量
c++·学习·ue5