题目:
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
.
题意:就是在一个已经排好序的单链表中,将其中有重复的元素去掉。此题一开始LZ考虑得很简单,应该只要用循环遍历每个节点,然后其中用HashSet来判断去重,如果出现重复的,那么就将这个重复的给去了。但是一开始我是用这个参数里的head在做,导致后来head指向尾节点,这样就会出错。后来经过同学提醒,我知道了应该设置一个current的节点(指针),应为向java这种面向对象的语言,它设置的对象存的都是地址,也就是说其实它放在内存中的是地址,而我新设一个节点,让它去做遍历,也只是在内存中的存放的地址变了,但是因为我还用head去指向头节点,所以这个并没有什么关系。
代码如下:
public class Solution
{
public ListNode deleteDuplicates(ListNode head) //这里的ListNode是单链表,就是非常普通的单链表
{
Set uniqueSet = new HashSet();
if(head == null || head.next == null)
return head;
else
{
ListNode current = head;
uniqueSet.add(current.val);
while(current.next != null)
{
if(uniqueSet.contains(current.next.val))
current.next = current.next.next;
else
{
uniqueSet.add(current.next.val);
current = current.next;
}
}
return head;
}
}
}