Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
分析,删除重复项,每个元素只出现一次,这里使用hash函数,判断节点值是否出现过
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
Map<Integer,Integer> x=new HashMap<Integer,Integer>();
ListNode H=new ListNode(0);
H.next=head;
ListNode p=H;
while(p.next!=null)
{
if(x.get(p.next.val)==null)
{
x.put(p.next.val,1);
p=p.next;
}
else
{
p.next=p.next.next;
}
}
return H.next;
}
}
时间: 2024-11-10 11:41:27