Reputation: 5660
I have a list of linkedlist's node. Basically references to node objects. Some of the references point to the same object. Now my question is on how to sort them.
Input :
List< node1, node3, node 4, node1, node2, node3>
Output:
List <node1, node1, node2, node3, node3, node4>
Order could be arbitraty ie
List <node3, node3, node2, node4, node1, node1>
, but atleast the adjacent nodes should be next to each other.
Also note, the sorting is not based on 'node value' but simply based on node references.
MORE REFERENCE:
I have a map, Map <headNode, tailNode>
. Since the linkedlist can intersect the map contains unique heads but does not contain unique tails. My intention is to sort the map based on 'value' and then walk through map with logic similar to if (tail at pos i != tail @ pos i + 1) then the 2 linkedlist done intersect and print them.
Upvotes: 2
Views: 149
Reputation: 4713
If you are plan to eliminate the duplicates, why don't you use HashSet
Upvotes: 1
Reputation: 129537
You can sort based on the System.identityHashCode()
value of each element in the list. You can implement a Comparator
as follows:
enum IdentitySort implements Comparator<Node> {
INSTANCE;
@Override
public int compare(Node n1, Node n2) {
return Integer.compare(System.identityHashCode(n1),
System.identityHashCode(n2));
}
}
Then, you can use Collections.sort()
:
Collections.sort(list, IdentitySort.INSTANCE);
Upvotes: 2