移除重复节点(简单)
2020年9月29日
题目来源:力扣
解题
- 哈希集合
记录非重复节点
/**
* 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 null;
Set<Integer> set=new HashSet<>();
//虚假头节点
ListNode t_head=head;
set.add(t_head.val);
while(t_head!=null){
while(t_head.next!=null && set.contains(t_head.next.val))
t_head.next=t_head.next.next;
if(t_head.next!=null && !set.contains(t_head.next.val))
set.add(t_head.next.val);
t_head=t_head.next;
}
return head;
}
}