Iam_Sandeep

Untitled

Nov 25th, 2025
590
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.56 KB | None | 0 0
  1. public static SinglyLinkedListNode condense(SinglyLinkedListNode head) {
  2.     if (head == null) return null;
  3.  
  4.     HashSet<Integer> seen = new HashSet<>();
  5.     SinglyLinkedListNode curr = head;
  6.     SinglyLinkedListNode prev = null;
  7.  
  8.     while (curr != null) {
  9.         if (seen.contains(curr.data)) {
  10.             // Duplicate → remove the node
  11.             prev.next = curr.next;
  12.         } else {
  13.             // First time seeing this value
  14.             seen.add(curr.data);
  15.             prev = curr;
  16.         }
  17.         curr = curr.next;
  18.     }
  19.  
  20.     return head;
  21. }
Advertisement
Add Comment
Please, Sign In to add comment