Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only
distinct
numbers from the original list.
For example,
Given
For example,
Given
1->2->3->3->4->4->5
, return
1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
错了一下午了,碰到重复数据在头或者在尾就跪,最后还是先用HashMap记录各个数字的重复次数,然后重新构造了一个链表.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
ListNode p = head;
while(p!=null){
if(map.get((Integer)(p.val)) == null)
map.put(p.val, 1);
else
map.put(p.val, map.get((Integer)(p.val)).intValue() + 1);
p = p.next;
}
ListNode newhead = new ListNode(0);
p = newhead;
while(head!=null){
if(map.get((Integer)(head.val)).intValue()==1){
p.next = new ListNode(head.val);
p = p.next;
}
head = head.next;
}
return newhead.next;
}
}