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;
    }
};
相关推荐
聆风吟º9 分钟前
【数据结构手札】顺序表实战指南(三):扩容 | 尾插 | 尾删
数据结构·顺序表·扩容·尾插·尾删
资深web全栈开发10 分钟前
LeetCode 2054:两个最好的不重叠活动 —— 从暴力到优化的完整思路
算法·leetcode
IT方大同10 分钟前
数组的初始化与使用
c语言·数据结构·算法
im_AMBER12 分钟前
Leetcode 84 水果成篮 | 删除子数组的最大得分
数据结构·c++·笔记·学习·算法·leetcode·哈希算法
AAA阿giao25 分钟前
从树到楼梯:数据结构与算法的奇妙旅程
前端·javascript·数据结构·学习·算法·力扣·
Salt_072826 分钟前
DAY 41 Dataset 和 Dataloader 类
python·算法·机器学习
点云SLAM29 分钟前
C++ 偏特化详解
开发语言·c++·c++模板·c++17·c++高级应用·c++偏特化·大型项目
长安er29 分钟前
LeetCode 124/543 树形DP
算法·leetcode·二叉树·动态规划·回溯
Sheep Shaun33 分钟前
STL:list,stack和queue
数据结构·c++·算法·链表·list
杜子不疼.33 分钟前
【LeetCode 153 & 173_二分查找】寻找旋转排序数组中的最小值 & 缺失的数字
算法·leetcode·职场和发展