leetcode 237. Delete Node in a Linked List ---java

题目:

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4after calling your function.

删除给定节点。

思路:

由于仅给出一个删除节点,不能通过得到上一节点进行删除,因此,选择改变给定节点的val进行操作。即:将该节点的val更改为下一节点的val值,并删除下一节点。

程序:

class Solution {
    public void deleteNode(ListNode node) {
        
        if( node != null){
            node.val = node.next.val;
            node.next = node.next.next;   
        }
    }
}

你可能感兴趣的:(leetcode 237. Delete Node in a Linked List ---java)