leetcode19题解

2025-10-21

leetcode19题解

题目

Given the head of a linked list, remove the nth node from the end of the list and return its head.

解题思路

虽然暴力遍历很快,但是我觉得我的递归调用很帅。

代码

/**
 * 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:
    int recursivelyDelete(ListNode* head, int n)
    {
        if(head==NULL) return 0;
        else {
            int ret=recursivelyDelete(head->next,n);
            cout<<ret<<" "<<head->val;
            if (ret==n){
                ListNode* p=head->next;
                head->next=head->next->next;
                delete p;

            }
            return ret+1;
        }
    }
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head->next==NULL&&n==1){
            return NULL;
        }
        else{
            int ret=recursivelyDelete(head,n);
            if(ret==n){
                ListNode* p=head;
                head=head->next;
                delete p;
            }
        }
        return head;
    }
};