[leetcode]82. Remove Duplicates from Sorted List

第一题:遍历链表,遇到重复节点就连接到下一个。

public ListNode deleteDuplicates(ListNode head) {
        if (head==null||head.next==null) return head;
        ListNode res = head;
        while (head.next!=null){
            if (head.val==head.next.val)
            {
                if (head.next.next!=null) head.next = head.next.next;
                else head.next = null;
            }
            else head = head.next;
        }
        return res;
    }

第二题:思路比较简单,设置一个超前节点作为head的前节点,往下遍历,遇到重复的就把超前节点连接到新的val节点。

public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode res = new ListNode(0);
        res.next = head;
        ListNode list = res;
        while (res.next!=null&&res.next.next!=null)
        {
            ListNode temp = res.next.next;
            if (res.next.val==res.next.next.val)
            {
                while (temp.next!=null&&temp.next.val==temp.val)
                {
                    temp = temp.next;
                }
                if (temp.next!=null) res.next = temp.next;
                else res.next = null;
            }
            else res =res.next;
        }
        return list.next;
    }

 当要经常删除第一个节点是,要设置一个超前节点

原文地址:https://www.cnblogs.com/stAr-1/p/8441120.html