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 -> 4 after calling your function.
删除一个节点,这题确实很简单,但乍一看可能没啥思路。只给出一个节点,而且要删除这个节点,常见的是找到前驱,然后让前驱的next指向要删除节点的下一个节点即可。这里头节点都没给出,显然不能这样做。
一个节点只能获取到下一个节点的信息,故采用了值替换。
public void deleteNode(ListNode node) {
if(node.next==null) {
return;
}
node.val = node.next.val;
node.next = node.next.next;
}