Leetcode-Remove Duplicates from Sorted List II(Java)

Question:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Thinking:

It’s similar with other linked list question. We should build a dummy node before the head. Hold three pointers to operate the next pointer of these nodes.

Solution:

public ListNode deleteDuplicates(ListNode head) {
    if (head == null)
        return head;
    ListNode dummy = new ListNode(head.val-1);
    dummy.next = head;
    ListNode pre = dummy;
    ListNode p = head;
    ListNode next = head.next;
    while (next != null){
        if (p.val == next.val){
            while (next != null && p.val == next.val){
                next = next.next;
            }
            pre.next = next;
            if (next == null){
                break;
            } else{
                p = next;
                next = next.next;
            }
        } else{
            pre = p;
            p = p.next;
            next = next.next;
        }
    }

    return dummy.next;
}