题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
import java.util.HashSet;
import java.util.Set;
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
if(pHead == null)
return null;
ListNode node = pHead;
ListNode pre = pHead;
Set<Integer> set = new HashSet<Integer>();
Set<Integer> set1 = new HashSet<Integer>();
while(node != null) {
if(set.contains(node.val)) {
set1.add(node.val);
pre.next = node.next;
node = node.next;
}else {
set.add(node.val);
pre = node;
node = node.next;
}
}
node = pHead;
pre = pHead;
while(node != null) {
if(set1.contains(node.val)) {
if(node == pHead) {
pHead = pHead.next;
node = pHead;
pre = pHead;
}else {
pre.next = node.next;
node = node.next;
}
}else {
pre = node;
node = node.next;
}
}
return pHead;
}
}