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;
    }
};
相关推荐
从琳开始989几秒前
优选算法——双指针(算法原理+力扣题)
算法·leetcode·职场和发展
从琳开始9893 分钟前
优选算法——滑动窗口(概念+解题模板+LeetCode例题讲解)
算法·leetcode·职场和发展
Nil2084 分钟前
leetcode 94二叉树的中序遍历
算法·leetcode·职场和发展
兔兔兔兔15 分钟前
记录C++ 8
开发语言·c++
不会就选b8 分钟前
算法日常・每日刷题
算法
一只小小的芙厨15 分钟前
最短路总结
数据结构·算法
致Great22 分钟前
OpenAI 又把 Codex 往前推了一步: 以后做 Agent,没必要都造一个聊天框
算法
脑子不好的小菜鸟1 小时前
秋招、实习 小知识点复习 (C/C++/Linux)—— 碎片时间可看
c++·求职招聘
aqiu1111112 小时前
【算法刷题】蓝桥杯/AtCoder:删除元素后的中位数问题(Symmetry / Median)
算法·蓝桥杯·排序·中位数
charlie1145141912 小时前
深探std::vector:三指针、扩容与迭代器失效
开发语言·c++·开源项目