日野弥生:勉強しよう

LeetCode 2095 - 删除链表的中间节点

发表于2025年01月31日

#链表 #双指针

技巧:快指针比慢指针每次多走一步,则快指针到底时,慢指针在中点处。在此题中,不管是奇数长度的链表和偶数长度的链表都一样。

class Solution {
public:
    ListNode* deleteMiddle(ListNode* head) {
        /* 如果链表为空,或者链表只有一个节点,都可以直接返回空 */
        if(!head || !head->next)
            return nullptr;
            
        ListNode *slowPrev = nullptr, *slow = head, *fast = head;
        while(slow && fast && fast->next)
        {
            slowPrev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        slowPrev->next = slow->next;
        delete slow;
        return head;
    }
};

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/delete-the-middle-node-of-a-linked-list/

上一篇

LeetCode 430 - 扁平化多级双向链表

下一篇

LeetCode 237 - 删除链表的节点