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;
    }
};
相关推荐
7 973 分钟前
C语言基础知识--文件的顺序读写与随机读写
java·数据结构·算法
2401_841003983 分钟前
Kubernetes 资源管理全解析
算法·贪心算法
exm-zem1 小时前
多用户图书管理系统
c++
☆璇1 小时前
【数据结构】排序
c语言·开发语言·数据结构·算法·排序算法
我要成为c嘎嘎大王1 小时前
【C++】初识C++(1)
开发语言·c++
艾莉丝努力练剑4 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途5 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
还债大湿兄6 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
珊瑚里的鱼9 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上9 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt