Delete nodes in the linked list
Problem-solving code (java)
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
1. Normal thinking (wrong thinking)
$. Normal idea: To delete a node node, let the node (2) before node point to the node after node (4)
*But! ! !
We cannot access the node before node, so we cannot change its point
[so this method is invalid]
2. Correct problem-solving ideas
-
The idea is explained in detail:
Because our purpose is to delete the value of the current node node, but not change the value of other nodes, and we can only access the nodes after node,
so we only need to overwrite the current node node with the value of the next node of node The value of, then delete the next node (delete the next node using the normal idea mentioned above) -
Implementation steps:
1>. Overwrite the value of the next node of node over the current node
2>. Point node to the (next.next) node
difficulty
【Change in logical thinking】
statement
- Author: ELE
- <Do not reprint without permission, welcome everyone to comment>