Having some problems with my given code. Thou it works accordingly, im required to implement the “transverse” & “transverseR” functions.
Also i have trouble understanding what the given function pointers are for:
Function pointers => void (*visit)(link)
void traverse (link ls, void (*visit)(link)) {
if (ls == NULL) {
return;
}
(*visit) (ls);
traverse (ls->next, visit);
return;
}
void traverseR (link ls, void (*visit)(link)) {
if (ls == NULL) {
return;
}
traverseR (ls->next, visit);
(*visit)(ls);
return;
}
void square (link l) {
// link tmp = NULL;
int container = l->item;
container = SQUARE(container);
l->item = container;
}
void squareAll (link ls){
link curr = ls;
while (curr != NULL){
square(curr);
curr = curr->next;
}
ls = curr;
}
These function pointers allows you to perform some custom actions using a function of your own on each list item as a list is being traversed. For example, you might write a function that decreases each node’s data:
The when you can call
traverse(list_head, decrease_item)to decrease a value of every item in a list. You can create a function for printing each element’s item and so on.Btw, in your code above you can rewrite
squareAllfunction in a more elegant manner: