Due to the frequent insertions and deletions at the head and tail of the linked list, I have chosen to use the linked list from the Java API. And the linked list will be ranked in descending order, i.e. 100,98,97,95,90
LinkedList<MyObject> mylinkedlist = new LinkedList<MyObject>();
Myobject new_value = new MyObject(96);
Occasionally I have to insert elements into this linked list(not at the head and tail). Because the linked list must be in descending order, I have to traverse the linked list in descending order from the head or ascending order from the tail and then insert it into a correct index.
I came up with an attempt as follow
int i;
for(int i=0; i<mylinkedlist.size(); i++)
{
if(mylinkedlist.get(num).getInt() <= new_value.getInt()){
break;
}
}
mylinkedlist.add(i,new_value)
I can just tell my code above is really poor. However, is there a way to optimize my code and avoid using break
and at the same time , also avoid traversing the entire linked list because it could be super long ?
It would be greatly appreciated if code example could be provided. Thanks.
UPDATE: Sincere apologies for not phrasing my questions properly. MY problem should be that given the linked list currently contains 100,98,97,95,90
, if I want to insert a new and different value, say 96
. How should one detect the index of the linked list such that the new value 96
can be inserted into it, while preserving the descending order of the linked list?
It is really important that the (1) descending order of the list and the (2) uniqueness of elements in the list are preserved in this problem.