Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
Hint
- Picture the list 1-> 5 - >9 - > 12. Removing 9 would make it look like 1-> 5 - > 12. You only have access to the 9 node. Can you make it look like the correct answer?
Solution
本题要我们删除链表内除了首尾外的任意一个结点,条件只有要删除的结点而没有给出链表的头结点,因此和以往的删除操作处理略有不同。我们可以用这样的思路,使用当前结点的下一个结点值覆盖当前结点,然后再删除当前结点的下一个结点即可。
public void deleteMiddleNode(ListNode node) {
if (node == null || node.next == null) return;
node.val = node.next.val;
node.next = node.next.next;
}