Delete the node java in the linked list

Please write a function to delete a given (non-end) node in a linked list. The only parameter passed into the function is the node to be deleted.

There is a linked list – head = [4,5,1,9], which can be expressed as:
Insert picture description here

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: Given the second node whose value is 5 in your linked list, then after calling your function , The linked list should be 4 -> 1 -> 9.
Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: Given the third node whose value is 1 in your linked list, then after calling your function , The linked list should be 4 -> 5 -> 9.

prompt:

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.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/delete-node-in-a-linked-list
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: At the beginning of this question, my idea was to find the previous one because the value is the only one, and then delete the specified one. As a result, I looked for a while and found that the head did not come in. I was stunned for a while, so I went to look. The problem solution, as a result, there is a brain teaser problem solution. It is indeed a new idea, and the time complexity is also low. The only disadvantage that is not a disadvantage is that it cannot be the tail node.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public void deleteNode(ListNode node) {
    
    
        node.val = node.next.val;
        node.next = node.next.next;

    }
}

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/112604596