LeetCode19. Remove Nth Node From End of List

文章目录

一、题目

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

Example 1:

Input: head = [1,2,3,4,5], n = 2

Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1

Output: []

Example 3:

Input: head = [1,2], n = 1

Output: [1]

Constraints:

The number of nodes in the list is sz.

1 <= sz <= 30

0 <= Node.val <= 100

1 <= n <= sz

Follow up: Could you do this in one pass?

二、题解

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) {
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* fast = dummyHead;
        ListNode* slow = dummyHead;
        n++;
        while(n-- && fast != nullptr){
            fast = fast->next;
        }
        while(fast != nullptr){
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return dummyHead->next;
    }
};
相关推荐
CoovallyAIHub几秒前
编码智能体做 CV 任务,实际能力到哪一步了?——五项视觉任务实测解读
深度学习·算法·计算机视觉
qq_283720051 分钟前
Qt QML 中为 ComBox设置鸿蒙字体(HarmonyOS Sans)——适配 Qt 5.6.x 与 Qt 5.12+
c++·qt·harmonyos
2501_945423542 分钟前
C++编译期多态实现
开发语言·c++·算法
2401_879693872 分钟前
设计模式在C++中的实现
开发语言·c++·算法
☆5666 分钟前
C++中的代理模式高级应用
开发语言·c++·算法
2301_818419017 分钟前
编译器命令选项优化
开发语言·c++·算法
m0_518019487 分钟前
C++图形编程(OpenGL)
开发语言·c++·算法
Jasmine_llq8 分钟前
《B4354 [GESP202506 一级] 假期阅读》
数据结构·算法·最值筛选算法(核心逻辑)·三元运算符简化分支算法·多输入顺序处理算法·整数算术运算算法·格式化输出算法
2301_8166512212 分钟前
自定义异常类设计
开发语言·c++·算法
weixin_4219226912 分钟前
C++与自动驾驶系统
开发语言·c++·算法