移除重复节点

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12684896.html

移除重复节点(148min)

题目链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/

示例1:

输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:

输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:

链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。

题解:

         方法:

                   1使用集合来存储列表中数,目的是可以筛选出列表中已经存在的数字,进行指针操作。

                    2.使用两个指针,一个指针是来删选列表中重复的数,另一个指针是选记录不是重复的指针。

        思路一:

       当列表中的数已在集合中,说明列表中当前这个数时重复的,此时fast指针指向断列表中下一个数继续判断。要是这个数不在集合中,说明这个数不是重复的数,加入集合中,并且把记录列表的指针low的next指向此时的fast指针,low向后移一位,fast也向后移一位.

代码如下:

class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if(head==null||head.next==null)
           return head;
        HashSet <Integer> set=new HashSet<Integer>();//定义一个集合,存放列表中的元素
        ListNode fast=head.next;
        ListNode low=head;
        set.add(head.val);
        while(fast.next!=null)
        {
            if(set.contains(fast.val))
            {
                
                fast=fast.next;
            }
            else
            {
                set.add(fast.val);
                low.next=fast;
                low=low.next;
                fast=fast.next;
            }
        }

        return low;
    }
}

但是这里结果不对,也没有想明白为啥,个人感觉自己代码写的挺对的。

          思路二:

                        是看别人写的,但是我自己按照数走一遍感觉不对。但是代码确是对的。我简直了。。。。。

                        说明:pre是头节点,cur是头节点的下一个节点。

                         思想:把头节点加入到集合中,当cur的值不在集合中时,就使pre指向下一个节点,cur指向pre的下一个节点,当cur当前的数已在集合中,那么使pre的next指向next的next,在把cur指向pre的next.我感觉不对的原因如下图中,当pre=3,cur=3时,此时cur的值是包含在集合中的,那么pre需要指向4,但是这时cur就指向null,最后一个节点就判断不了了。我,太难了。

 代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        HashSet<Integer> set = new HashSet<Integer>();
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        set.add(head.val);
        ListNode pre = head;
        ListNode cur = head.next;
        while(cur!=null){
            int tmp = cur.val;
            if(set.contains(tmp)){
                pre.next=pre.next.next;
            }else{
                set.add(cur.val);
                pre=pre.next;
            }
            cur=pre.next;
        }
        return head;
    }
}

  写此代码的链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/solution/javati-jie-setyong-fa-by-baolibin/

原文地址:https://www.cnblogs.com/ping2yingshi/p/12684896.html