leetcode

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

public ListNode deleteDuplicates(ListNode head) {
        //safeguard
        ListNode newHead = new ListNode(0);
        ListNode current = head;
        newHead.next = current;

        while(current!=null&&current.next!=null) {
            ListNode next = current.next;
            if (next.val == current.val) {
                //next until current and next value are different
                while (next!=null && next.val==current.val) {
                    next = next.next;
                }
                current.next = next;
             }
            //current should point to next
            current = next;
        }

        return newHead.next;
   }