Java Recursive Solution


  • 0
    Z

    For clarity I have separated the solution into two methods, the provided method and getTrueHead(ListNode) method. The latter returns the first unique node starting from the provided one. For example:
    getTrueHead( 2,2,2,2,2,2,3,4) = 3,
    getTrueHead(1,2,3,4 )= 1,
    getTrueHead(2,2,2,2,2) = null
    Thus, using this method we just bind consequent unique node elements and then return the first of them.

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
    		head = getTrueHead(head);
     	        if(head == null || head.next == null || head.next.next == null) return head;
    		ListNode par = head;
    		while(par != null){
    			ListNode cur = par.next;		
    			par.next = getTrueHead(cur);
    			par = par.next;
     		}
    		
    		return head;
        }
    
        public ListNode getTrueHead(ListNode head){
    		if(head == null || head.next == null) return head;
    		if(head.val != head.next.val) return head;
    		ListNode cur = head;
    		ListNode next = cur.next;
    		int val = cur.val;
    		while(next != null && val == next.val ) next = next.next;
    		head = next;
    		return getTrueHead(head);
        }
    }

Log in to reply
 

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