Detailed explanation of deleting nodes in the linked list

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)

Insert picture description here

$. 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

Insert picture description here

  • 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>

Guess you like

Origin blog.csdn.net/weixin_48557384/article/details/109268169