Review the insertion of the linked list
A node of the linked list is composed of a data field and a pointer field , and the address of the pointer field is the address of the next element. So how do we need to insert or delete an element?
First look at the original linked list structure and prepare to insert node x into the linked list.
At this time, we need to save the address of node n (300) first, and store the address of node n in the pointer field of node m, and assign this value to the pointer field of node x. (x->next=m->next) becomes as shown in the figure below.
At this time, connect the m node and the x node. m->next=x. As shown in the figure below.
Seeing this, some friends may have questions. If it is an empty list, this way of inserting will not work (you can draw a picture and see it), yes, that's the point to say, sentry .
What is the sentinel node?
We can first think about the reasons why the empty linked list cannot use the first scheme. Because it has no nodes, we naturally cannot get its address, so we add a head node. Then the structure of the empty linked list is as shown in Figure 4, non-empty linked list The structure is shown in Figure 5.
Review the deletion of the linked list
The above briefly introduces the linked list of the lead node, which is also applicable when deleting, so we will directly use the linked list of the lead node to explain in the future. Let's look directly at the delete node graph.
1Leetcode237 delete the node of the linked list
Please write a function to delete a given (non-end) node in a linked list, and you will only be given the requested node to be deleted.
There is a linked list - head = [4,5,1,9], which can be expressed as:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: Given the second node in your linked list with a value of 5, after calling your function, the linked list should become 4 -> 1 -> 9.
Description:
The linked list contains at least two nodes.
The values of all nodes in the linked list are unique.
The given node is not the end node and must be a valid node in the linked list.
Don't return any results from your function.
Think about it for a minute!
The effect is better!
Conventional routine
Find the pointer of the previous node of the node to be deleted .
Point the pointer to the next node to be deleted. As shown in Figure 7 below.
Look carefully
Found that, the title did not tell us the previous node, it doesn't matter, we can find a way to construct a node, please take a look.
The goal is to delete 5, and the final result is [4,1,9]. We assign the node 1 behind the 5 nodes that need to be deleted to it, as shown in Figure 8.
Hey, now the value of two nodes is 1. No matter which one is deleted, we can get the result, but the second node 1 is not convenient for us to delete, but the third node 1 is still easy. Assuming that the p pointer points to the deleted node, it is directly p.next=p.next.next. As shown in Figure 9.
1c++ version