“This is the second day of my participation in the November Gwen Challenge. See details of the event: The last Gwen Challenge 2021”.

The title

Write a function to delete a specific node in a singly linked list. When designing functions, note that you cannot access the head node of the list, only the node to be deleted.

The topic data ensures that the node to be deleted is not the last node.

Enter: head = [4,5,1,9], node = 5

Output:,1,9 [4]

Description: Specify the second node in the list with a value of 5, then the list strain will be 4 -> 1 -> 9 after calling your function

Enter: head = [4,5,1,9], node = 1

Output: [4, 9]

Description: Specify the third node in the list whose value is 1, then the list strain is 4 -> 5 -> 9 after calling your function

Thought analysis

In general, the operation for deleting nodes is as follows:

  1. Point next of the last node to be deleted to the next node
  2. Release the node to be deleted

However, this problem only tells us the node to be deleted, but does not tell us the previous node of the node to be deleted, so we cannot delete the node in the normal way.

However, according to the principle of the riddle on the riddle, we need to pay attention to the problem: the problem data ensure that the node to be deleted is not the last node. The difference between a normal node and a trailing node is that only the trailing node has no next node, but the trailing node can be removed easily because we can simply release the trailing node.

It looks like we need to do something about the last node. Since we need a node to be deleted to have the value of the last node, we can swap the node to be deleted with the next node, so that the node can be deleted.

ListNode nodeNext = node.next;
node.val = nodeNext.val;
node.next = nodeNext.next;
Copy the code

conclusion

There is no algorithm knowledge point (or no algorithm template can be used directly, so it will cause some trouble.)