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.
LeetCode 237. Delete Node in a Linked List 删除链表中的节点(Java)_第1张图片
Note:

  • The linked list will have at least two elements.
  • All of the nodes’ values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

解答:

题目比较简单,但是要注意!题目中没有给出待删除的链表,没有head,只有node,所以不能对node的上一节点进行操作。
因此,将下一节点向前挪,即将下一个节点的值传给当前节点node,然后删除下一节点即可。

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

你可能感兴趣的:(LeetCode)