问题一:在O(1)时间内删除链表节点
public class E18DeleteOneListNode {
private static class ListNode{
int value;
ListNode nextNode;
}
public static void deleteOneListNode(ListNode head, ListNode nodeToBeDeleted){
if (head == null || nodeToBeDeleted == null)
return;
if (nodeToBeDeleted.nextNode != null){
ListNode node = nodeToBeDeleted.nextNode;
nodeToBeDeleted.value = node.value;
nodeToBeDeleted.nextNode = node.nextNode;
}
else if (head == nodeToBeDeleted){
head = null;
}
else{
ListNode node = head;
while(node.nextNode != nodeToBeDeleted){
node = node.nextNode;
}
node.nextNode = null;
}
}
}
问题二:在链表中删除重复的节点
public class E18DeleteDuplicateListNode {
private static class ListNode{
int value;
ListNode nextNode;
}
public static void deleteDuplication(ListNode head){
if (head == null)
return;
ListNode preNode = null;
ListNode node = head;
while(node != null){
ListNode nextNode = node.nextNode;
if (nextNode != null && nextNode.value == node.value){
int value = node.value;
ListNode toBeDeleted = node;
while(toBeDeleted != null && toBeDeleted.value == value){
nextNode = toBeDeleted.nextNode;
toBeDeleted.nextNode = null;
toBeDeleted = nextNode;
}
if (preNode == null){
head = nextNode;
}
else
preNode.nextNode = nextNode;
node = nextNode;
}
else{
preNode = node;
node = node.nextNode;
}
}
}
}