遍历一遍链表完成链表节点去重,没有使用额外空间

主要思路

(1)链表遍历过程中,判断每个节点是否为重复节点,寻找不重复的节点用链表连接。
(2)如果头节点是重复节点,那么寻找链表中第一个出现的不重复节点作为头节点,如果整个链表都没有不重复节点,那么返回null。

    public ListNode deleteDuplication(ListNode head)
    {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        ListNode tmp = head;
        ListNode cur = head.next;
        boolean isDupNode = cur.val == tmp.val;
        boolean isHeadDup = cur.val == tmp.val;//开头是否有重复
        while(cur != null){
            ListNode nextNode = cur.next;
            while(nextNode != null && cur.val == nextNode.val){
                isDupNode = true;
                nextNode = nextNode.next;
            }
            if(!isDupNode){//如果不是重复节点就接上链表,如果节点是重复的,直接跳过
                if(isHeadDup){//开头是否重复,如果是,就找链表中第一个非重复节点作为头节点
                    head = cur;
                    tmp = cur;
                    isHeadDup = false;
                }
                tmp.next = cur;
                tmp = tmp.next;
            }
            isDupNode = false;
            cur = nextNode;
        }
        if(isHeadDup){//如果链表中没有不重复的节点,直接返回null
            return null;
        }
        tmp.next = cur;
        return head;

    }