I have a function find(x) in my linked list, that search through the listfor the value and return an Iterator pointing to the first node contaning value x. if x is not found in the list, it returns an Iterator pointing to NULL.
it should be a linear search.
would you please help me fix this code.

this is what I wrote, but it dosent work.
thanks

//find function
template<typename T>
Iterator<T> LinkedList<T>::find(T value) 
{


	Node<T>* pos = NULL;
	Iterator<T> res=pos.position;

	Node<T>* current = first;
	Iterator<T> iter=current.position;

	while (current != NULL) {
		if(current->data===value)
			return iter;
		else
			current=current->next;
	}
	return res; 
}

The iterators I've worked with are defined like LinkedList<T>::iterator iter and use begin() and end() to iterate through the list.

First welcome to Daniweb.

Second, when posting code on Daniweb please enclose it in code tags to maintain the indentation you (hopefully) use in the code you write. Use of the tags is discussed in the watermark to the message box you type in before you start typing as well as in the sticky messages at the top of the board.

I suppose the easiest answers to your question might be one of the following:

1) I'm aware of the = operator and the == operator but I've never seen a === operator, though that may be a typo from typing rather than copy/paste.

2) I see where iter is assigned a value outside the while loop, but I don't see where that value is changed anwhere in the while loop.

3) I'm not aware that pointers have members so pos.position seems likely to be an error. pos->position might be valid, but the interface of Node isn't provided so I can't say. Please post the Node interface or indicate the type of the variable called position.

4) If you are trying to write your own list class that mimics the STL list class, and therefore want to use iterators, fine. If not, I'd advise just sticking with pointers and not try to mix the pointers and iterators within the program as you seem to be doing.

5) You should be able to assign NULL to an iterator directly, and not need to go through an intermediary variable.

6) There's really no reason to have res at all, that I can see.

Here's how I might rewrite the posted function if I were trying to mimic the STL list class.

template<T>  
iterator LinkedList::find(T value) 
{
   LinkedList<T>::iterator start = begin();
   LinkedList<T>::iterator stop = end();
   
   for( ; start != stop; ++start)
      if(start->data == value)
        break;    

   return start; 
}

It's been so long since I tried to mimic anything within STL that I won't garauntee the syntax of that first line of the code, but it's close.

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.