请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
Write a function to delete a node (except the tail) in a singly linked list, given only access to that 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;
}
}