题目描述:
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
我的代码:
/**
* 删除链表中的重复元素
* @param pHead 原链表的头结点
* @return 返回删除重复元素之后的新的链表的头结点
*/
public ListNode deleteDuplication(ListNode pHead) {
//LinkedHashMap可以按照输入的顺序进行输出
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
ListNode current = pHead;
//遍历一遍原链表,将元素出现的次数存储在map中
while (current != null) {
if (!map.containsKey(current.val)) {
map.put(current.val, 1);
} else {
int times = map.get(current.val);
times++;
map.put(current.val, times);
}
current = current.next;
}
ListNode newHead = null;
ListNode point = null;
boolean isHead = true;
Set<Integer> set = map.keySet();
Iterator<Integer> it = set.iterator();
//根据map中存的值,只用出现一次的值来构造新的链表
while (it.hasNext()) {
int temp = it.next();
if (map.get(temp) == 1) {
ListNode currentNode = new ListNode(temp);
if (isHead) {
newHead = currentNode;
point = currentNode;
isHead = false;
continue;
}
point.next = currentNode;
point = currentNode;
}
}
return newHead;
}
通过这道题需要学习到的知识点是LinkedHashMap,这个数据结构可以保证map中存储的顺序和添加进去的顺序是一样的。