0

Hi,
I'm working on this program where I have to do some updating. In this case, I have to add a new item to the linked list, and it should be in a sorted fashion (ascending). I am trying to use my find() function, which returns the previous node (*ptrPrev). But, my insert4update() function is not doing what I want it to do. Any ideas? Pls?

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;
}

template <class DataType>
bool List<DataType>::insert4update(DataType& item2){
	bool found = false;
	Node<DataType> *ptrPrev = NULL;
	Node<DataType> *ptr = start;
	found = find(item2, ptrPrev);
	if(found)
		return found;
	else{
		if(ptrPrev == NULL){
			ptr->info = item2;
			numItems++;
			found = true;
		}	
		else{
			ptrPrev->next->info = item2;
			numItems++;
			found = true;
		}
	}
	return found;
}

Thanks :)

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Greywolf333
0
if(item > ptr->info){  			
ptrPrev = ptr;//step 1			
ptr = ptr->next;//step 2   		
}
else			
found = true;

Won't this "find" an item even if it's not equal to the item? Maybe it should be "if (item != ptr->info)".

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.