题目:
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.
思路:
由于仅给出一个删除节点,不能通过得到上一节点进行删除,因此,选择改变给定节点的val进行操作。即:将该节点的val更改为下一节点的val值,并删除下一节点。
程序:
class Solution {
public void deleteNode(ListNode node) {
if( node != null){
node.val = node.next.val;
node.next = node.next.next;
}
}
}