Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static SinglyLinkedListNode condense(SinglyLinkedListNode head) {
- if (head == null) return null;
- HashSet<Integer> seen = new HashSet<>();
- SinglyLinkedListNode curr = head;
- SinglyLinkedListNode prev = null;
- while (curr != null) {
- if (seen.contains(curr.data)) {
- // Duplicate → remove the node
- prev.next = curr.next;
- } else {
- // First time seeing this value
- seen.add(curr.data);
- prev = curr;
- }
- curr = curr.next;
- }
- return head;
- }
Advertisement
Add Comment
Please, Sign In to add comment