剑指offerNo.13,比较直观的是O(n)的算法,代码如下
package com.zjy.sword2offer;
class ListNode{
int val;
ListNode next;
}
public class DeleteNode {
public ListNode deleteNode(ListNode head, ListNode key){
if(head==null||key==null)
return null;
if(head.next==null)
head = null;
ListNode previous = null;
ListNode current = head;
while(current.val!=key.val && current.next!=null)
{
previous = current;
current = current.next;
}
if(previous==null)
{
head = current.next;
current.next = null;
}
else
{
if(current.next==null)
{
previous.next = null;
}
else
{
previous.next = current.next;
current.next = null;
}
}
return head;
}
}
要实现O(1)复杂度,即不需要知道要删除节点的前一个节点,那么可以把要删除节点的后一个节点复制到要删除的节点上,再删除该节点
public void deleteNode2(ListNode head, ListNode delete){
if(head==null||delete==null)
return;
if(head.equals(delete))
{
head = delete = null;
}
else if(delete.next!=null)
{
delete.val = delete.next.val;
delete.next = delete.next.next;
delete.next.next = null;
}
else
{
ListNode tmp = head;
while(tmp.next!=delete)
{
tmp = tmp.next;
}
tmp.next = null;
delete = null;
}
}