移除重复节点

题目描述:
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

方法一:借助辅助空间set

class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        Set<Integer> set=new HashSet<>();
        set.add(head.val);
        ListNode cur=head;
        while(cur!=null&&cur.next!=null){
            int x=cur.next.val;
            if(set.contains(x)){
                cur.next=cur.next.next;
            }else{
                cur=cur.next;
                set.add(x);
            }
        }
        return head;
    }
}

方法二:利用冒泡排序思想

class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        ListNode cur=head;
        while(cur!=null){
            ListNode p=cur;
            while(p.next!=null){
                if(p.next.val==cur.val){
                    p.next=p.next.next;
                }else{
                    p=p.next;
                }
            }
            cur=cur.next;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42174669/article/details/106241252
今日推荐