I need in c a bool insert for an ordered linked list I tried
I need in c++ a bool insert for an ordered linked list. I tried
template <class T>
bool OListType<T>::insert(const T& item)
{
NodeType<T> *temp, *curr, *prev;
temp = new NodeType<T>;
temp->info = item;
temp->link = NULL;
if (this->head == NULL) {
this->head = temp;
this->head->link = NULL;
++this->count;
}
else {
curr = this->head;
prev = NULL;
while (curr != NULL && curr->info < item) {
prev = curr;
curr = curr->link;
}
if (curr == NULL) {
prev->link = temp;
++this->count;
}
else {
temp->link = curr;
prev->link = temp;
++this->count;
}
}
return true;
}
and it does not work. Can you help fix it or make a new one?
Solution
Your code is absolutely correct but a small change needs to be done. The following is the updated version of your code. Try this. it will work for sure.
template <class T>
bool OListType<T>::insert(const T& item)
{
NodeType<T> *temp, *curr, *prev;
temp = new NodeType<T>;
temp->info = item;
temp->link = NULL;
if (this->head == NULL) {
this->head = temp;
this->head->link = NULL;
++this->count;
}
else {
curr = this->head;
prev = NULL;
while (curr != NULL && curr->info < item) {
prev = curr;
curr = curr->link;
}
if (prev == NULL) { //My Changes here. Here we are trying to insert at the first/head position if the item is the smallest element
temp->link=this->head;//changed
this->head=temp;// changed
++this->count;
}
else {
temp->link = curr;
prev->link = temp;
++this->count;
}
}
return true;
}

