I have a problem in a sorted linked list. I cannot insert an item in constant time. If possible, how can I solve it?
And this complex time complexity is Big-O (N)
template <class ItemType> void SortedType<ItemType>::InsertItem(ItemType item) { NodeType<ItemType>* newNode; NodeType<ItemType>* predLoc; NodeType<ItemType>* location; bool moreToSearch; location = listData; predLoc = NULL; moreToSearch = (location != NULL); while (moreToSearch) { if (location->info < item) { predLoc = location; location = location->next; moreToSearch = (location != NULL); } else moreToSearch = false; } newNode = new NodeType<ItemType>; newNode->info = item; if (predLoc == NULL) { newNode->next = listData; listData = newNode; } else { newNode->next = location; predLoc->next = newNode; } length++; }
source share