Illustration of LeetCode brush problem plan

1. Write it first

Hand-drawn comic book series officially launched!!” LeetCode brush plan “here it comes!!

Today is the eleventh issue, strive for one every day, at most two days, welcome everyone to supervise me…

I’m a pigeon…

2, the topic

So let’s look at the problem first,

n

I’m just going to go through the implementation of the scan, the two-pointer approach, so without further ado, here we go.

3, the body

All right, let’s take a look.

First, create a virtual header, attach it to the header, and define two Pointers.

First moves n positions, and then the two Pointers start moving at the same time, so that the interval between the two Pointers is fixed at n. As long as first moves to the end node, the next position after second is the node to be deleted.

Finally return the next location of the virtual node, not the head node, because the head node may change, but the virtual node must not change!!

4, code,

/** * 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) {
        auto fic=new ListNode(0);
        fic->next=head;
        auto first=fic,second=fic;
        while(n--){
            first=first->next;
        }
        while(first->next){
            first=first->next;
            second=second->next;
        }
        second->next=second->next->next;
        returnfic->next; }};Copy the code

If lucky enough to help you, please help me a [praise], to a [attention]! I would appreciate an encouragement along the way.

If you want more resources, please follow @I’m Guan Xiaoliang, MAX~