在一个排序的链表中,如何删除重复的节点?
链表1->2->3->3->4->4->5,处理后为 1->2->5
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;
//交由GC处理
toBeDeleted.nextNode = null;
toBeDeleted = nextNode;
}
//更改节点指向
if (preNode == null){
head = nextNode;
}
else
preNode.nextNode = nextNode;
node = nextNode;
}
//未发现则将指针向前推进
else{
preNode = node;
node = node.nextNode;
}
}
}
}
网友评论