Eclipse implements the hashCode() function for a singly linked list's Node class the following way:
class Node{
int val;
Node next;
public Node(int val){
this.val = val;
next = null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((next == null) ? 0 : next.hashCode());
result = prime * result + val;
return result;
}
}
Now hashCode() for a node is dependent on the hash code of the nodes that follow it.
So, every call of hashCode() will take amortized linear time in the length of the linked list. Thus using a HashSet<Node> will become unfeasible.
One way to get around this is to cache the value of the hashCode in a variable(call it hash) so that it is computed only once. But even in this case, the hash will become invalid once any node's val is changed. And again it will take linear time to modify the hashCode of nodes that follow the current node.
So what are some good ways of implementing hashing for such a linked list Node?
return val;, since it's anint; although, that depends on how you implement.equals()ll1.equals(ll2)istrue, then you definitely don't want theirhashCode()s to be the same. So implement it in a way that respects that contract.[x] -> [x] -> NULLversus[x] -> [x] -> [x] -> NULL; they only containxbut one is longer. Consider that.