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;
    }
};
相关推荐
叩码以求索3 分钟前
统计按位或能得到最大值的子集数目(一)
数据结构·算法
tachibana228 分钟前
hot100 数组中的第K个最大元素(215)
java·数据结构·算法·leetcode
txzrxz38 分钟前
单调队列讲解
数据结构·c++·算法·单调队列
绝世番茄1 小时前
HarmonyOS List 上拉加载更多(LoadMore)深度实战指南
华为·list·harmonyos·鸿蒙
WWTYYDS_6661 小时前
JsonCpp超详细使用教程
c++
不会就选b1 小时前
算法日常・每日刷题--<快排>4
算法
Keven_111 小时前
算法札记:树状数组的用途
数据结构·算法
Joey_friends2 小时前
指纹authenticate流程图
android·java·c++
用户677437175812 小时前
C++函数参数传递方式详解:string、string&、const string、const string&该怎么选?
算法
小小晓.2 小时前
C++小白记:C风格字符串和数组用法
c语言·开发语言·c++