The find function in a linked list

Hi

I'm having trouble completing the function bool list::find(int x) which returns true if x is in the list and otherwise false. The function is associated with the struct

struct node
{
int data;
node *next;
};

Can someone assist me in this

Thanks.
Probably something like:

1
2
3
4
5
6
7
8
9
10
bool list::find(int x){
	node* p=first;//first is the first element of the list
	do{
		//x is in the list
		if(first->data==x){
			return true;}
		p=p->next;}while(first->next!=NULL);//go to the next element
	//we've reached the end of the list, so x isn't in it
	return false;}

Oh, and to make your code look like this ^^^, use the [ code ]<your code here> [ /code ] tags (without the spaces)
Last edited on
this code is good but it crashes if you the value is not the first one. Any recommendations?
If the value isn't the first one? That's weird... Could you show more code?
struct node
{
int data;
node *next;
};

bool list::find(int x)
{
//returns true if x is in list and otherwise false

}


int main()
{
char choice = ' ';
node *start = NULL;
node *last = NULL;
list myList;
int value;
.....
}

private :
node *first;// start of list
node *last; // last in list

Now in the main() is a loop for a menu that gives the user an option to keep entering values until they decide to stop and then the bool function will search for a particular value which has been input by the user.

Hope this helps ;-)
Last edited on
There is a bug in PiMaster's function.
wizard25 wrote:
this code is good but it crashes if you the value is not the first one. Any recommendations?
Try to write your own function, this is the logic:
__Traverse the container (in this case your list)
__For every element ask if that cell is equal to the query value
____true: tell that you find it, and stop the traverse
__If you end the traverse then the value is not in the container.
Last edited on
Topic archived. No new replies allowed.