I need help with this problem, here.
I have 2 functions: "find4update" is supposed to compare the incoming parameter "item2" to the item that is already in the linked list, and return the value of "found". And my second function "deletNode" should use that "find4update" function and delete the found item from the list. I dont know what I'm doing wrong.
Any ideas? Please?

template <class DataType>
bool List<DataType>::find4update(DataType item2){
	bool found = false;
	Node<DataType> *ptr = start;
	while((ptr != NULL) && (!found)){
		if(ptr->info == item2){
			found = true;
		}
		ptr = ptr->next;
	}
	return found;
}

template <class DataType>
bool List<DataType>::deleteNode(DataType &item2){
	bool found = false;
	Node<DataType> *ptr = start;
	found = find4update(item2);
	if(found)
		return found;
	else{
		while(ptr != NULL && ptr->info != item2){
			if(ptr->info == item2){
				delete ptr;
			}
			ptr = ptr->next;
		}
	}
}

Thanks!
By the way, this is just a part of my whole code. It would take a whole lot of space if posted it all :)

Edited 5 Years Ago by super-duper: n/a

delete ptr doesn't remove the node from the list, it simply releases the memory. The list still refers to a dangling pointer. deleteNode is also rather inefficient because it traverses the list twice: first to find a match and again to do the deletion. You can roll these together:

template <class DataType>
bool List<DataType>::deleteNode(DataType& item2)
{
    if (start != 0) {
        Node<DataType> *it = start;

        if (it->item == item2) {
            // Unlink the head node
            start = start->next;

            // Release the old head node's memory
            delete it;

            return true;
        }
        else {
            while (it->next != 0 && it->next->item != item2)
                it = it->next;

            if (it->next != 0) {
                Node<DataType> *save = it->next;

                // Unlink the found node from the list
                it->next = it->next->next;

                // Release the node's memory
                delete save;

                return true;
            }
        }
    }

    return false;
}
This article has been dead for over six months. Start a new discussion instead.