Algorithms and Data Structures/Coding Practices

[LinkedList] CCI 2.1

brightlightkim 2022. 5. 20. 13:29

2.1 Write code to remove duplicates from an unsorted linked list.

 

The first algorithm that came to my mind was storing data to Set and see if it shows an error when inserting a value to see if it exists. If it already exists then remove the node. 

 

Just checked the last Index.

public Node deleteDuplicatedNodes(Node head){
    Node n = head;
    Set<Integer> set = new HashSet<>();
    set.add(n.data);

    while(n.next != null){
        if (set.contains(n.next.data)){
            // It means it already exists.
            if (n.next.next != null) {
                n.next = n.next.next;
            } else {
                n.next = null;
                break;
            }
        } else {
            set.add(n.next.data);
        }
        n = n.next;
    }
    return head;
}

 

Solution:

public void deleteDups(Node n) {
    HashSet<Integer> set = new HashSet<>();
    Node previous = null;
    while (n!=null){
        if (set.contains(n.data)){
            previous.next = n.next;
        } else {
            set.add(n.data);
            previous = n;
        }
    }
}

I thought that this was brilliant because it stored the previous that it makes code more succinct and readable. 

'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글

CCI 4.1 Route Between Nodes  (0) 2022.05.31
[Stacks and Queues] CCI 3.1  (0) 2022.05.22
[LeetCode] 36. Valid Sudoku  (0) 2022.05.19
[LeetCode] 11 Container With Most Water  (0) 2022.05.18
[Array and Strings] CCI 1.1  (0) 2022.05.18