Delete a node from a linked list

Write a function that removes a given (non-trailing) node from a linked list. The only argument passed to the function is the node to be deleted.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/de… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: Brain teaser

I didn’t react at first time, why didn’t I give head node? The solution is to change the value and next of the node to the value and next of the next node at the point to be deleted.

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; }}}Copy the code

There is only one heroism, and that is to love life after recognizing the truth of life.