A golang solution


  • 1
    N
    func deleteDuplicates(head *ListNode) *ListNode {
        var prev *ListNode
    	now := head
    
    	if head != nil && head.Next != nil {
    		m := make(map[int]struct{})
    
    		for now != nil{
    			_, ok := m[now.Val]
    			if ok {
    				prev.Next = now.Next
    				now = prev.Next
    			} else {
    				m[now.Val] = struct{}{}
    				prev = now
    				now = now.Next
    			}
    		}
    	}
    	return head
    }

  • 0
    R

    Recursive version:

    func deleteDuplicates(head *ListNode) *ListNode {
        var hold *ListNode
        if head == nil { 
            return hold 
        }
        hold = head
        helper(head, head.Next)
        return hold
    }
    
    func helper(prev *ListNode, curr *ListNode) {
        if curr != nil {
            if curr.Val == prev.Val {
                prev.Next = curr.Next
                helper(prev, prev.Next)
            } else {
                helper(curr, curr.Next)
            }
        }    
    }
    

Log in to reply
 

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