Question & Answer: Write a boolean c++ function that searches for the first occurnece of a given integer i…..

Write a boolean c++ function that searches for the first occurnece of a given integer in a linked list and moves the node containing the integer to the front of the list. The function returns false if the data is not located in the list. It returns true if the data has been located and the node containing the data has been moved to the front of the list.

Expert Answer

 

The function search searches if the element is present or not. Since I don’t know C++ I would be using my own linked list in C. They are almost the same. The malloc function is used to allocate memony and free is used to delete a node(in this case). The structure of the linked list is defined as follows:

struct node{

int data;

struct node *link;

}

Search searches for the element. If present it returns true and brings it to the front and then returns the function.

bool search(node *start, int s)

{

struct node *p = start, *tmp;

int p=1;

while(p!=null)

{

if(p->data==s)

{

if(start->data == s)

return true;

else

{

p = start;

while(p->link!=null)

{

if(p->link->data ==s)

{

tmp=p->link;

p->link=tmp->link;

free(tmp);

}

}

}

tmp=(struct node *)malloc(sizeof (struct node));

tmp->data=s;

tmp->link = start;

start=tmp;

return true;

}

}

}

In the first while loop I will search for the element using a simple while and if statement. If it is found. Then I begin to delete it using the free. After delete there arise 2 cases: The element is the first element or it is not. If it is the first element then I dont need to do anything as it is already done else I delete the element and then place it in the first using a simple code.

Still stressed from student homework?
Get quality assistance from academic writers!