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;
    }
};
相关推荐
naruto_lnq4 分钟前
C++中的工厂方法模式
开发语言·c++·算法
一切尽在,你来6 分钟前
C++多线程教程-1.2.3 C++并发编程的平台无关性
开发语言·c++
千逐-沐风14 分钟前
SMU-ACM2026冬训周报2nd
算法
寄存器漫游者33 分钟前
数据结构 C语言 顺序栈
java·c语言·数据结构
郝学胜-神的一滴40 分钟前
深入解析Linux网络编程之bind函数:从基础到实践的艺术
linux·服务器·网络·c++·websocket·程序人生
m0_7482331742 分钟前
C#与C语言:5大核心语法共性
java·jvm·算法
雾岛听蓝1 小时前
C++11 列表初始化与右值引用核心解析
开发语言·c++·经验分享
痴儿哈哈1 小时前
C++与硬件交互编程
开发语言·c++·算法
小O的算法实验室1 小时前
2024年ESWA SCI1区TOP,异构无人机配送问题的集成多目标优化方法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
日拱一卒——功不唐捐1 小时前
循环队列+双端队列(C语言)
c语言·数据结构