image.png
一開始用雙指針锨用,出現(xiàn)誤區(qū),解不出來
用set也解不出來
利用LinkedHashMap<node.val,count>來解題隘谣,先將所有node的val都放入map增拥,如果已經(jīng)存在就count++,然后去遍歷整個map,將count==1的所有node.val作為新的節(jié)點寻歧,連在后面
Map<Integer,Integer> map=new LinkedHashMap<Integer,Integer>();//普通的hashmap無法按插入的順序來刪除掌栅,如果想按插入的順序來輸出,就利用LinkedHashMap
思路比較簡單码泛,直接看代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur=new ListNode(0);
ListNode head1=cur;
ListNode cur1=head;
Map<Integer,Integer> map=new LinkedHashMap<Integer,Integer>();//普通的hashmap無法按插入的順序來刪除猾封,
//如果想按插入的順序來輸出,就利用LinkedHashMap
while(cur1!=null){
if(map.containsKey(cur1.val)){
int temp=map.get(cur1.val);
temp++;
map.put(cur1.val,temp);
}else{
map.put(cur1.val,1);
}
cur1=cur1.next;
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue()==1){
cur.next=new ListNode(entry.getKey());
cur=cur.next;
}
}
return head1.next;
}
}