Sort by

recency

|

719 Discussions

|

  • + 0 comments

    Simplest Py3 solution:

    def removeDuplicates(self,head):
            if head is None:
                return head
                
            start = head
            curr = head
            
            while curr.next is not None:
                if curr.next.data == curr.data:
                    curr.next = curr.next.next
                else:
                    curr = curr.next
                    
            return start
    
  • + 0 comments

    Java

       public static Node removeDuplicates(Node head) {
             if(head==null||head.next==null){
        return head;
      }
    
      List<Integer> list = new ArrayList<>();
      Node current = head;
      while(current.next!=null){
        list.add(current.data); 
         if(list.contains(current.next.data)){
            // skip the next node
            current.next = current.next.next;                  
            }else {
                current = current.next;
            }         
      }
      return head;
    }
    
  • + 0 comments

    My solution in Python 3 using dictionary

    def removeDuplicates(self,head):
        d = {}
        cur = n = head
    
        while n is not None:
            if n.data not in d.keys():
                d[n.data] = True
                cur = n
            else:
                cur.next = n.next
            n = n.next
        return head
    
  • + 0 comments

    C#

    public static Node removeDuplicates(Node head)
        {
            //Write your code here
            //My answer
            if (head.next is not null)
            {
                Node next = head.next;
                while (next.next is not null)
                {
                    Node next2 = next.next;
                    if (next.data == next2.data)
                    {
                        next.next = next2.next;
                    }
                    else
                    {
                        next = next.next;
                    }
                }
    
                next = head.next;
                if (head.data == next.data)
                {
                    head.next = next.next;
                }
    
            }
    
            return head;
        }
    
  • + 0 comments

    This will remove all duplicates, not just the adjacent ones.

    def removeDuplicates(self, head: Node | None):
        current_node = head
        s = set((current_node.data, ))
    
        while current_node.next:
            if current_node.next.data not in s:
                s.add(current_node.next.data)
                current_node = current_node.next
            else:
                current_node.next = current_node.next.next
    
        return head