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;
    }
};
相关推荐
MZ_ZXD0014 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
快去睡觉~6 小时前
力扣73:矩阵置零
算法·leetcode·矩阵
岁忧6 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
小欣加油6 小时前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
zylyehuo9 小时前
C++基础编程
c++
月盈缺9 小时前
学习嵌入式的第二十二天——数据结构——双向链表
数据结构·学习·链表
猿究院--王升9 小时前
jvm三色标记
java·jvm·算法
一车小面包9 小时前
逻辑回归 从0到1
算法·机器学习·逻辑回归
tt55555555555510 小时前
C/C++嵌入式笔试核心考点精解
c语言·开发语言·c++
lg_cool_10 小时前
Qt 中最经典、最常用的多线程通信场景
c++·qt6.3