[LeetCode] 19. 删除链表的倒数第N个节点 19. Remove Nth Node From End of List

本文已收录于 LeetCode刷题 系列,共计 28 篇,本篇是第 3 篇

本文已收录到:LeetCode刷题 专题

视频讲解

[bilibili cid=”” page=”1″]840006760[/bilibili]

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode dummy(0);
        ListNode* tail = &dummy;

        tail->next = head;
        ListNode* fast = &dummy;
        ListNode* slow = &dummy;

        for (int i = 0; i < n; i++)
        {
            fast = fast->next;
        }
        while (fast->next != nullptr)
        {
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return dummy.next;
    }
};

 

作者: 高志远

高志远,24岁,男生

发表评论

邮箱地址不会被公开。