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 twelfth 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,

void deleteNode(ListNode* node)
Copy the code

It is a deleted node, not a head node, plus a single linked list, can not find the precursor node, the normal method is invalid.

But we can copy the value of the next node to the current node, and then delete the next node.

All right, cut the crap. Here we go.

3, the body

All right, let’s take a look.

The list is 4, 5, 1, 3, and the node you want to remove is 5, so the general operation is get and then DELETE, and that’s OK. However, as mentioned above, the node is passed in, so the method used here is to replace the node to be deleted with the next location of the node to be deleted, which perfectly solves the problem!

4, code,

Two ways to write, one is normal, one is C++ specific!

Routine:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; * /
class Solution {
public:
    void deleteNode(ListNode* node) { node->val=node->next->val; node->next=node->next->next; }};Copy the code

C++ specific:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; * /
class Solution {
public:
    void deleteNode(ListNode* node) { *(node)=*(node->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~