LeetCode19 Delete the Nth node from the bottom of the linked list, the LeetCode road of HERODING

Given a linked list, delete the nth node from the bottom of the linked list, and return the head node of the linked list.

Example:

Given a linked list: 1->2->3->4->5, and n = 2.

When the penultimate node is deleted, the linked list becomes 1->2->3->5.

Description:

The given n guarantees are valid.

Advanced:

Can you try to use a scan to achieve it?

Problem-solving idea: The
most common method should be to traverse and calculate the length len of the linked list first, and then delete the node at len-n. The second method is the reverse when the stack operation is performed. Here I use It is a recursive operation, the idea is very clear, the code is very simple, if you want to traverse the realization, then the idea can be a fast or slow pointer, the fast pointer runs n times before the slow pointer, so that it can be implemented once convenient, the code is provided as recursion Way, the code is as follows:

/**
 * 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 cur;
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    
    
        if(!head){
    
    
            return nullptr;
        }
        head -> next = removeNthFromEnd(head -> next, n);
        cur ++;
        if(cur == n){
    
    
            return head -> next;
        }
        return head;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/109141052