import java.util.HashMap;
import java.util.Map;
/**
* 链表中删除重复的节点
*
* 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
* 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
*/
public class JZ056DeleteDuplicationInListNode {
public static ListNode deleteDuplication(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return pHead;
}
Map<Integer, Integer> map = new HashMap<>();
while (pHead != null) {
map.put(pHead.val, map.getOrDefault(pHead.val, 0) + 1);
pHead = pHead.next;
}
ListNode curHead = new ListNode(-1);
ListNode cur = curHead;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
cur.next = new ListNode(entry.getKey());
cur = cur.next;
}
}
return curHead.next;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode cur1 = new ListNode(2);
head.next = cur1;
ListNode cur2 = new ListNode(3);
cur1.next = cur2;
ListNode cur3 = new ListNode(3);
cur2.next = cur3;
ListNode cur4 = new ListNode(4);
cur3.next = cur4;
ListNode cur5 = new ListNode(4);
cur4.next = cur5;
ListNode cur6 = new ListNode(5);
cur5.next = cur6;
cur6.next = null;
ListNode cur = deleteDuplication(head);
while (cur != null) {
System.out.println(cur.val);
cur = cur.next;
}
}
}