I have a list of random "pointers"
- "A,B,C,D,E,F"
They belong into N different linked lists
- "A->C->D", "B->E", "F"
The only information I can get from the pointers is that the "child" knows the "parent" but not the other way around.
My current implementation to sort them into their own respective linked list is as below.
Would appreciate if i can get some pointers on optimizing the code below or if my approach to it is wrong.
for (Pointer i: listOfPointers) {
if (!i.hasParent())
// no parent, its a root node
rootNodes.add(i.getId());
else {
// parent -> child
parentChild.put(i.getParent().getId(),i.getId());
}
}
// iterate through the head/roots
for (String i : rootNodes) {
LinkedList<String> templist = new LinkedList<>();
LinkedList<Map<String,String>> temp = new LinkedList<>();
String tempnow = i;
//construct our linked list, start by the head and getting the child until we have nothing left
do{
if (templist.size() == 0)
System.out.println("Parent - " + tempnow);
else
System.out.println("Child - " + tempnow);
templist.add(tempnow);
if (parentChild.containsKey(tempnow))
tempnow = parentChild.get(tempnow);
else
break;
}while(true);
linkedListHashMap.put(i, templist);
}