计算机 · 2024年7月25日 0

面试题之删除倒数第n个节点

https://leetcode.cn/problems/remove-nth-node-from-end-of-list

思路:先搞两个距离为n的节点,然后让两个节点保持距离同时向后遍历,当后面那个节点变为nullptr时,前面那个节点就是要删除的节点,另外再搞个单独的变量记录前面那个节点的prev。链表头的值需要分类讨论一下,根据删除的节点是否是链表头返回不同的值。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* prev = nullptr;
        ListNode* deleted = head;
        ListNode* tail = deleted;
        ListNode* res = nullptr;
        while (n--) {
            tail = tail->next;
        }
        while(tail != nullptr) {
            prev = deleted;
            deleted = deleted->next;
            tail = tail->next;
        }
        if (prev != nullptr) {
            prev->next = deleted->next;
            delete deleted;
            res = head;
        } else {
            res = deleted->next;
            delete deleted;
        }
        return res;
    }
};