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;
    }
};
相关推荐
wyhwust5 小时前
codeblocks程序调试
c++
Tisfy5 小时前
LeetCode 2913.子数组不同元素数目的平方和 I:第一题先常数很大的O(n^2)
算法·leetcode·题解·模拟·暴力
罗湖老棍子5 小时前
[USACO05NOV] Asteroids G(洛谷-P7368)
算法·图论·二分图匹配·最大匹配·最小顶点覆盖
从小白到软工5 小时前
4-1 指针
c语言·开发语言·数据结构·经验分享·ai编程
AI技术新视界5 小时前
Harness^2:递归自进化智能体Harnessing框架
人工智能·深度学习·算法·harness·rsi
这个DBA有点耶5 小时前
MySQL B-tree索引并发控制优化:写密集场景的锁瓶颈与内核级解法
java·数据库·程序人生·算法·database·dba
爱读书的小胖6 小时前
Deaf Grandma:C 语言三版代码分析
算法
傲世仙尊6 小时前
运算符重载-operator函数与五个不能重载的符号
c++
信奥卷王6 小时前
[GESP202503 六级] 环线(含视频)
算法
傲世仙尊6 小时前
赋值运算符重载-从无到有与从有到有六大函数收官
c++