给定单向链表的一个头指针和节点指针,定义一个函数在O(1)时间删除该节点。
public class ListNode {
public int value;
public ListNode next;
}
public class Test {
public void test(ListNode headNode, ListNode targetNode) {
if (headNode == null || targetNode == null) {
return;
}
if (headNode == targetNode) {//目标节点是头节点
headNode = headNode.next;
return;
}
if (targetNode.next == null) {//目标节点是尾节点
ListNode tmp = head;
while(tmp.next != targetNode) {
tmp = tmp.next;
}
tmp.next = null;//删除targetNode;
} else {//目标节点是中间节点
ListNode tmp = head;
while(tmp.next != targetNode) {
tmp = tmp.next;
}
tmp.next = tmp.next.next;//删除targetNode;
targetNode = null;
}
}
}
网友评论