Java Straightforward solution, same idea as remove duplicates from array


  • 0
    J

    Use the same idea as remove duplicates from Array, did use some extra space, but easy to understand.

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            ListNode dummy = new ListNode(-1);
            ListNode node = dummy;
            int cur = head.val;
            int count = 1;
            head = head.next;
            while(head != null){
                if(head.val == cur){
                    count++;
                }else{
                    if(count == 1){
                        node.next = new ListNode(cur);
                        node = node.next;
                    }
                    cur = head.val;
                    count = 1;
                }
                head = head.next;
            }
            if(count == 1){
                node.next = new ListNode(cur);
            }
            return dummy.next;        
        }
    }
    

Log in to reply
 

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