题目
Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。
如果可以获取头节点或这个节点的上一个节点,那么这个问题就很简单了。但是题目只给了要删除的节点,链表是单链表,没有获取上个节点的办法。《编程之美》中提供了一个解决办法:替换节点的值,让下个节点和当前节点交换内容,再删除下个节点。
思路很巧妙!有思路的话这个题目就非常简单了,代码如下:
public class Solution {
/*
* @param node: the node in the list should be deletedt
* @return: nothing
*/
public void deleteNode(ListNode node) {
if(node == null){
return;
}
if(node.next != null){
ListNode next = node.next;
int t = node.val;
node.val = next.val;
next.val = t;
node.next = next.next;
}
}
}