解题思路:
- Map记录每个元素出现的次数
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
// 新建数组链表
ArrayList<Integer>res=new ArrayList<>();
// Map记录元素出现的次数
Map<Integer,Integer>map = new HashMap<>();
// 当前节点
ListNode curr = head;
while(curr!=null){
// 判断map中是否已存在当前元素的键
if(map.containsKey(curr.val)){
// 如果已存在,则+1
map.put(curr.val,map.get(curr.val)+1);
}else{
// 如果不存在,则添加至map中
map.put(curr.val,1);
}
curr =curr.next;
}
//遍历map,将key为1的元素添加至新链表中
for(Object obj:map.keySet()){
if((int)map.get(obj)==1){
res.add((int)obj);
}
}
int i=0;
ListNode first = new ListNode(0);
ListNode tt=first;
Collections.sort(res);
while(i<res.size()){
ListNode temp=new ListNode((int)res.get(i));
tt.next=temp;
tt=temp;
i++;
}
return first.next;
}
}
2. 双指针
- 当前节点curr和下一个节点值相等时,执行while循环找到下一个不相等的节点,给prev
- 当前节点curr和下一个节点不相等时,prev和curr都移动遍历
prev = ListNode(0)
curr = head
while head and head.next:
if head.val == head.next.val:
head =head.next
while head.next and head.val == head.next.val:
head = head.next
prev.next =head.next