This is part of my linked list program.
I need to change the data(node) with a new one when it is found (using the find function. And in other case I need to delete the found item using deleteNode() function, once the matching item is found.
But, it is not happening. I have been playing with it for hours now, still cannot figure it out. Any ideas?

//for finding the item + sorting the linked list
template <class DataType>
bool List<DataType>::find(DataType item, Node<DataType>* &ptrPrev){
	bool found = false;
	Node<DataType> *ptr = start;
	while((ptr != NULL)&&(item > ptr->info)&&(!found)){
		if(item > ptr->info){  
			ptrPrev = ptr;//step 1
			ptr = ptr->next;//step 2   
		}else
			found = true;
	}
	return found;
}

//once the right movie is found, then it's info is updated by this function.
template <class DataType>
bool List<DataType>::updateData(DataType &newItem){
	bool found = false;
	Node<DataType> *ptr = start;
	Node<DataType> *prevNode = NULL;
	found = find(newItem, prevNode);
	if(found){
		if(prevNode == NULL){
			ptr = start;
			ptr->info = newItem;
		}else{
			prevNode->next->info = newItem;
		}found = true;
	}
	return found;
}

//it deletes the found item from the linked list.
template <class DataType>
bool List<DataType>::deleteNode(DataType& item){
	bool found = false;
	Node<DataType> *ptr = start;
	Node<DataType> *ptrPrev = NULL;
	found = find(item, ptrPrev);
	if(found){
		if(ptrPrev != NULL){
			ptr = ptrPrev->next;
			ptrPrev->next = ptr->next;
		}else{
			ptr = start;
			start = ptr->next;
		}
		delete ptr;
		numItems--; 
	}
	return found;
}

Which part isn't working? Did you try debugging by looking at whether the correct node is found, or not? If the correct node isn't found, then what happens in find() ? If it is found, what goes wrong in deleteNode() ?

I think that at line 6, you meant to write:

while((ptr != NULL) && (item >= ptr->info) && (!found)) {

Notice the >= at in the second comparison. Otherwise, this function will always output false. Hint: You should always turn on all the warnings when compiling. This code would have given a warning as such "line 11 can never be reached" because the condition for entering an iteration is the same as for the if-statement, so the compiler would be smart enough to see that (and compilers don't miss typos like humans are so good at missing).

The rest looks alright. At line 49, "delete ptr;", if your implementation of the Node's destructor also destroys the next Node, that could be a memory problem (if it doesn't then it's OK). You could just set ptr->next to NULL just before the delete if you need to fix that.

Found the problem. That while loop condition was the problem.

Thanks guys :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.