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;
    }
};
相关推荐
依然鸣6 分钟前
PTA团体程序设计天梯赛L2真题讲解L2-001-004
经验分享·学习·算法·深度优先·pat考试
一米阳光86616 分钟前
软考(中级)软件设计师核心笔记(8)数据结构——图
数据结构·笔记·职场发展·软考·软件设计师·中级职称
SNAKEpc1213814 分钟前
OpenGL(十三)- Mip贴图
c语言·c++·图形渲染·贴图
杨航 AI2 小时前
** AI 面试算法 50 题清单**,不是单纯的 LeetCode 题号列表,而是按照“**考察概率 × 面试价值 × 你当前准备方向**”排序
算法·leetcode·面试
m0_720245018 小时前
1543.统计好三元组(简单)
开发语言·算法
To_OC9 小时前
LC 560 和为 K 的子数组:前缀和配哈希表,这对组合我是真的服了
javascript·算法·程序员
hans汉斯9 小时前
《软件工程与应用》期刊推荐&10月版面征稿中
图像处理·人工智能·深度学习·算法·音视频·软件工程
叠层归一研究院10 小时前
AGI 系统(八):符号范畴嵌入函子 — SymCat ↪ C_M107 严格化
c语言·开发语言·人工智能·算法·transformer·agi
其美杰布-富贵-李11 小时前
08 进阶评估指标与算法特定指标
人工智能·算法
.道阻且长.11 小时前
5.LeetCode算法习题讲解--双指针--有效三角形的个数
算法·leetcode·职场和发展