一、问题描述:
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.
二、解决思路:
最容易想到的是遍历这个链表,但是时间复杂度是O(N)
如何在O(1)的时间遍历呢? 我们只需要把要删除节点p的下一个节点q的内容复制给改节点,并把p的下一个节点指向q的下一个节点。然后删除q即可
三、代码:
public class Solution {
public void deleteNode(ListNode node) {
ListNode p = node.next;
node.val = p.val;
node.next = p.next;
}
}