LeetCode—面试题:移除重复节点(哈希集合)

移除重复节点(简单)

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;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108861989