The find function in a linked list

Nov 6, 2010 at 5:02am
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.
Nov 6, 2010 at 7:00am
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 Nov 6, 2010 at 7:46am
Nov 6, 2010 at 8:33am
this code is good but it crashes if you the value is not the first one. Any recommendations?
Nov 6, 2010 at 8:49am
If the value isn't the first one? That's weird... Could you show more code?
Nov 6, 2010 at 8:55am
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 Nov 6, 2010 at 9:00am
Nov 6, 2010 at 4:48pm
There is a bug in PiMaster's function.
Nov 6, 2010 at 6:30pm
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 Nov 6, 2010 at 6:32pm
Topic archived. No new replies allowed.