2
头图

Delete the node in the linked list

Title description: 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.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/delete-node-in-a-linked-list/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Brain teasers
I didn't respond at the first time, why didn't I give the head node? ? ? After thinking for a while, I would like to understand why the parameter is not the end of the node. The solution is to change the value of the node to be deleted and next to the value of the next node of the node to be deleted and next.
public class LeetCode_237 {
    public static void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(4);
        head.next = new ListNode(5);
        ListNode node_1 = new ListNode(1);
        head.next.next = node_1;
        head.next.next.next = new ListNode(9);

        System.out.println("before deleteNode");
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
        deleteNode(node_1);
        System.out.println("after deleteNode");
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }
}
[Daily Message] There is only one kind of heroism in the world, which is to still love life after recognizing the truth of life.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!