Home > Net >  What does this function do? I understand the recursion aspect but am confused with the following ope
What does this function do? I understand the recursion aspect but am confused with the following ope

Time:06-10

class Node{
 public:
 int data;
 Node* next;
};
int func(Node* node, int number){
  if(node){ //whilst the node does not equal null pointer
    if(node->data > 0) // if the data is greater than 0 
      return func(node->next, number) - node->data; // this is where i get confused...
    else if(node->data < 0)
      return func(node->next, number)   node->data;
    else
      return func(node->next, number   node->data)   number;
 }
 return 0;
}

I see that it does a recursive call to the function to use the following node in the sequence, then it subtracts the child nodes data from the parent node? Is my understanding thus far correct? What is the function trying to achieve? In my mind I was thinking the function is trying to set the data of all nodes in the linked list to 0? Would that be a correct assumption.

CodePudding user response:

subtracts the child nodes data from the parent node

No, it subtracts node->data from the result of the recursive call.

What is the function trying to achieve?

Ask the author. What we can tell you is what it does achieve. I am suspicious of the author's understanding of this function because number node->data appears where node->data is known to be 0.

The first two conditions are the same as subtracting the absolute value of each node->data, and the last condition adds number every time there is a 0.

  • Related