Share my 12-line Java code


  • 1
    M
    public ListNode deleteDuplicates(ListNode head) {
            ListNode dummy = new ListNode(0); dummy.next = head;
            for (ListNode p = dummy; p.next!=null; ) {
                ListNode q = p.next;
                if (q.next==null || q.next!=null&&q.val!=q.next.val) { p = p.next; }
                else {
                    ListNode r = q;
                    while (r!=null && r.val==q.val) { r = r.next; }
                    p.next = r;
                }
            }
            return dummy.next;
    }

  • 0
    J

    I like your code, it's simple and easy to understand.
    But I think this is better.

    public ListNode deleteDuplicates(ListNode head) {
    	ListNode dummy = new ListNode(0); 
    	dummy.next = head;
    	
        for (ListNode pre = dummy; pre.next!=null; ) {
            ListNode q = pre.next;
            if (q.next==null || (q.next!=null && q.val!=q.next.val)) { pre = pre.next; }
            else {
                ListNode r = q.next.next;
                while (r!=null && r.val==q.val) { r = r.next; }
                pre.next = r;
            }
        }
        
        return dummy.next;
        
    }

  • 0
    M

    yes, you are right! i have improved my code style and other aspects recently. thanks for reminding me these!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.