题目描述
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1
输入:[1, 2, 3, 3, 2, 1] 输出:[1, 2, 3]
示例2
输入:[1, 1, 1, 1, 2] 输出:[1, 2]
做题思路
借助set集合去重,若遇到set集合中已经包含的元素,则在链表上去掉该元素;否则将新元素添加进set集合,指针后移。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeDuplicateNodes(ListNode head) {
if(head==null) return head;
ListNode newHead=head; //存储初始头节点
Set<Integer> set=new HashSet<>(); //set集合用于去重
set.add(head.val); //将链表首元素添加进去,以便进行后续的判断
while(head!=null&&head.next!=null){
if(set.contains(head.next.val)){
head.next=head.next.next; //若set集合中已包含该元素,那么就在链表中去掉该元素
}else{
set.add(head.next.val); //否则将该元素添加进去
head=head.next; //指针后移
}
}
return newHead;
}
}